# library(dplyr)
# library(ggplot2)
# library(readstata13)
# library(rstudioapi)
# library(tidyr)
# library(dotwhisker)
# library(psych)
# library(stargazer)
# library(kableExtra)
# library(gridExtra)

set.seed(42)

# These need to be specified for the User
outdir_tables <-"~/Desktop/jop replication/"
outdir_figures <-"~/Desktop/jop replication/"

# Read Data
dat <- read.dta13(file = "~/Desktop/jop replication/unifiedanalysisdataset_recoded.dta")

dat$d_income <- as.numeric(dat$d_income)
dat$i_taxes1 <- as.numeric(dat$i_taxes1)
dat$i_taxes2 <- as.numeric(dat$i_taxes2)
dat$i_health3 <- as.numeric(dat$i_health3)
dat$i_01_immigration5 <- as.numeric(dat$i_01_immigration5)

dat$d_networth_total = NA
dat$d_networth_total[dat$d_networth_total1==1]=1
dat$d_networth_total[dat$d_networth_total2==1]=2
dat$d_networth_total[dat$d_networth_total3==1]=3
dat$d_networth_total[dat$d_networth_total4==1]=4
dat$d_networth_total[dat$d_networth_total5==1]=5
dat$d_networth_total[dat$d_networth_total6==1]=6
dat$d_networth_total[dat$d_networth_total7==1]=7

dat$union <- dat %>%
  pull(d_union) %>%
  plyr::mapvalues(., c("Formerly",
                       "Not now and never",
                       "Yes, currently"),
                  c(0,1,2)) %>%
  as.numeric()

dat <- dat %>%
  mutate(sample = ifelse(sample==1,"Donor",sample),
         sample = ifelse(sample==2,"Affluent",sample),
         sample = ifelse(sample==3,"Gen Pop",sample))


############################################
############################################
# MAIN FIGURE 1: Differences in Donor, Affluent, and General Population Policy Views on Domestic Issues by Party:
############################################
############################################

# Variable list - General Policies - must be in same order!
varlist_general <- c("fa_all",
                     "f_01_minwagejoint", 
                     "i_01_taxes1",
                     "f_01_tanfjoint",
                     "f_01_sumenvironment",
                     "i_01_health3",
                     "f_01_abortionjoint",
                     "i_01_rguncontrol"
                     )
varlist_names <- c(fa_all="Factor Score",
  f_01_minwagejoint="Increase Minimum Wage",
  i_01_taxes1="Incr. Top Marginal Tax Rate",
  f_01_tanfjoint="Increase TANF Spending",
  f_01_sumenvironment="Pro Environmentalism",
  i_01_health3="Incr. Govt Role in Health Care",
  f_01_abortionjoint="Fewer Abortion Restrictions",
  i_01_rguncontrol="More Gun Control")

textsize <- .6

# Republicans Regression
dat1a <- dat %>%
  filter(republican==1) %>%
  mutate(sample=as.factor(sample)) %>%
  mutate(sample=relevel(sample, ref="Gen Pop"))

rawdat1a <- dat1a %>%
  dplyr::select(sample,varlist_general) %>%  
  pivot_longer(names_to = "Variable", cols = varlist_general) %>%
  dplyr::select(sample,Variable,value) %>%
  drop_na()

reg1a <- rawdat1a %>%
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ sample, data = .))) %>% # run model for each variable
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(model=recode(model,
                      sampleAffluent = "Affluent",
                      sampleDonor = "Donor")) %>%
  arrange(factor(model, levels=c("Donor","Affluent"))) %>% 
  arrange(factor(term, levels=varlist_general))%>%
  mutate(model=factor(model, levels=c("Donor", "Affluent"))) %>%
  mutate(term=recode(term,
                     fa_all="Factor Score",
                     f_01_minwagejoint="Increase Minimum Wage",
                     i_01_taxes1="Incr. Top Marginal Tax Rate",
                     f_01_tanfjoint="Increase TANF Spending",
                     f_01_sumenvironment="Pro Environmentalism",
                     i_01_health3="Incr. Govt Role in Health Care",
                     f_01_abortionjoint="Fewer Abortion Restrictions",
                     i_01_rguncontrol="More Gun Control")) %>%
  mutate(term=factor(term, levels=c("Factor Score", 
                                    "Increase Minimum Wage",
                                    "Incr. Top Marginal Tax Rate",
                                    "Increase TANF Spending",
                                    "Pro Environmentalism",
                                    "Incr. Govt Role in Health Care",
                                    "Fewer Abortion Restrictions",
                                    "More Gun Control"))) %>%
  mutate(LCI=estimate-std.error*1.96) %>%
  mutate(UCI=estimate+std.error*1.96)

diff1a <- rawdat1a %>%
  filter(sample == "Donor" | sample == "Affluent") %>%
  mutate(sample=relevel(sample, ref="Affluent")) %>% 
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ sample, data = .))) %>%
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(tstat = format(abs(round(statistic,digits=2)),nsmall=2)) %>%
  mutate(term=recode(term,
                     fa_all="Factor Score",
                     f_01_minwagejoint="Increase Minimum Wage",
                     i_01_taxes1="Incr. Top Marginal Tax Rate",
                     f_01_tanfjoint="Increase TANF Spending",
                     f_01_sumenvironment="Pro Environmentalism",
                     i_01_health3="Incr. Govt Role in Health Care",
                     f_01_abortionjoint="Fewer Abortion Restrictions",
                     i_01_rguncontrol="More Gun Control")) %>%
  dplyr::select(term,tstat)

reg1a = left_join(reg1a,diff1a)

reg1a_daonly <- rawdat1a %>%
  filter(sample != "Gen Pop") %>%
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ sample, data = .))) %>% # run model for each variable
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(model=recode(model,
                      sampleDonor = "Difference")) %>%
  arrange(factor(term, levels=varlist_general)) %>%
#  mutate(model=factor(model, levels=c("Donor", "Affluent"))) %>%
  mutate(term=recode(term,
                     fa_all="Factor Score",
                     f_01_minwagejoint="Increase Minimum Wage",
                     i_01_taxes1="Incr. Top Marginal Tax Rate",
                     f_01_tanfjoint="Increase TANF Spending",
                     f_01_sumenvironment="Pro Environmentalism",
                     i_01_health3="Incr. Govt Role in Health Care",
                     f_01_abortionjoint="Fewer Abortion Restrictions",
                     i_01_rguncontrol="More Gun Control")) %>%
  mutate(term=factor(term, levels=c("Factor Score", 
                                    "Increase Minimum Wage",
                                    "Incr. Top Marginal Tax Rate",
                                    "Increase TANF Spending",
                                    "Pro Environmentalism",
                                    "Incr. Govt Role in Health Care",
                                    "Fewer Abortion Restrictions",
                                    "More Gun Control"))) %>%
  mutate(LCI=estimate-std.error*1.96) %>%
  mutate(UCI=estimate+std.error*1.96)

# Democrats Regression
dat1b <- dat %>%
  filter(democrat==1) %>%
  mutate(sample=as.factor(sample)) %>%
  mutate(sample=relevel(sample, ref="Gen Pop"))

rawdat1b <- dat1b %>%
  dplyr::select(sample,varlist_general) %>%  
  pivot_longer(names_to = "Variable", cols = varlist_general) %>%
  dplyr::select(sample,Variable,value) %>%
  drop_na()

reg1b <- rawdat1b %>%
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ sample, data = .))) %>% # run model for each variable
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(model=recode(model,
                      sampleAffluent = "Affluent",
                      sampleDonor = "Donor")) %>%
  arrange(factor(model, levels=c("Donor","Affluent"))) %>% 
  arrange(factor(term, levels=varlist_general))%>%
  mutate(model=factor(model, levels=c("Donor", "Affluent"))) %>%
  mutate(term=recode(term,
                     fa_all="Factor Score",
                     f_01_minwagejoint="Increase Minimum Wage",
                     i_01_taxes1="Incr. Top Marginal Tax Rate",
                     f_01_tanfjoint="Increase TANF Spending",
                     f_01_sumenvironment="Pro Environmentalism",
                     i_01_health3="Incr. Govt Role in Health Care",
                     f_01_abortionjoint="Fewer Abortion Restrictions",
                     i_01_rguncontrol="More Gun Control")) %>%
  mutate(term=factor(term, levels=c("Factor Score", 
                                    "Increase Minimum Wage",
                                    "Incr. Top Marginal Tax Rate",
                                    "Increase TANF Spending",
                                    "Pro Environmentalism",
                                    "Incr. Govt Role in Health Care",
                                    "Fewer Abortion Restrictions",
                                    "More Gun Control"))) %>%
  mutate(LCI=estimate-std.error*1.96) %>%
  mutate(UCI=estimate+std.error*1.96)

diff1b <- rawdat1b %>%
  filter(sample == "Donor" | sample == "Affluent") %>%
  mutate(sample=relevel(sample, ref="Affluent")) %>% 
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ sample, data = .))) %>%
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(tstat = format(abs(round(statistic,digits=2)),nsmall=2)) %>%
  mutate(term=recode(term,
                     fa_all="Factor Score",
                     f_01_minwagejoint="Increase Minimum Wage",
                     i_01_taxes1="Incr. Top Marginal Tax Rate",
                     f_01_tanfjoint="Increase TANF Spending",
                     f_01_sumenvironment="Pro Environmentalism",
                     i_01_health3="Incr. Govt Role in Health Care",
                     f_01_abortionjoint="Fewer Abortion Restrictions",
                     i_01_rguncontrol="More Gun Control")) %>%
  dplyr::select(term,tstat)

reg1b = left_join(reg1b,diff1b)

reg1b_daonly <- rawdat1b %>%
  filter(sample != "Gen Pop") %>%
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ sample, data = .))) %>% # run model for each variable
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(model=recode(model,
                      sampleDonor = "Difference")) %>%
  arrange(factor(term, levels=varlist_general)) %>%
  #  mutate(model=factor(model, levels=c("Donor", "Affluent"))) %>%
  mutate(term=recode(term,
                     fa_all="Factor Score",
                     f_01_minwagejoint="Increase Minimum Wage",
                     i_01_taxes1="Incr. Top Marginal Tax Rate",
                     f_01_tanfjoint="Increase TANF Spending",
                     f_01_sumenvironment="Pro Environmentalism",
                     i_01_health3="Incr. Govt Role in Health Care",
                     f_01_abortionjoint="Fewer Abortion Restrictions",
                     i_01_rguncontrol="More Gun Control")) %>%
  mutate(term=factor(term, levels=c("Factor Score", 
                                    "Increase Minimum Wage",
                                    "Incr. Top Marginal Tax Rate",
                                    "Increase TANF Spending",
                                    "Pro Environmentalism",
                                    "Incr. Govt Role in Health Care",
                                    "Fewer Abortion Restrictions",
                                    "More Gun Control"))) %>%
  mutate(LCI=estimate-std.error*1.96) %>%
  mutate(UCI=estimate+std.error*1.96)

##############
# Now Make figure
##############
nrows <- length(varlist_general)
offset <- .2

pdf(file="~/Desktop/jop replication/MAIN_Figure1.pdf")

plot(x=c(-.4,.25),y=c(1,2*length(varlist_general)+5),type="n",axes=FALSE,
     xlab="Difference from Copartisan \n  General Population Mean (and 95% CI)",
     ylab="",
     main = "Average Policy Differences \n Among Donors, Affluent, and General Public")
abline(v=seq(-.3,.15,by=.05),lty=2,col="light grey")
abline(v=0)
axis(1,at=seq(-.3,.2,by=.05),
     labels=c(-.3,-.25,-.2,-.15,-.1,-.05,0,.05,.1,.15,.2))

# democrats
for(i in 1: length(varlist_general)){
  donor_row <- reg1b %>%
    filter(term == varlist_names[varlist_general[nrows-i+1]], model == "Donor")
  affluent_row <- reg1b %>%
    filter(term == varlist_names[varlist_general[nrows-i+1]], model == "Affluent")
  
  text(x=0.2,y=i+1,labels=donor_row$tstat,cex=.75)
  
  # point estimate
  points(x=donor_row$estimate, y=i+1+offset,pch=16)
  points(x=affluent_row$estimate, y=i+1-offset, col = "GREY", pch = 18)
  
  segments(x0 = donor_row$LCI, y0 = i+1+offset, x1 = donor_row$UCI, y1 = i+1+offset)
  segments(x0 = affluent_row$LCI, y0 = i+1-offset, x1 = affluent_row$UCI, y1 = i+1-offset, col = "grey")
}

text(labels=rev(varlist_names),x=rep(-.4,times=length(varlist_general)),
     y=1+seq(1,length(varlist_general)),cex=textsize,pos=4)
text(labels = "Democrats", x = -.4, y = 5.5,srt=90)

legend(-.2, 11, legend=c("Donors", "Affluent"), col=c("black","light grey"), pch=c(16,18),cex=.75)

# republicans
for(i in 1: length(varlist_general)){
  donor_row <- reg1a %>%
    filter(term == varlist_names[varlist_general[nrows-i+1]], model == "Donor")
  affluent_row <- reg1a %>%
    filter(term == varlist_names[varlist_general[nrows-i+1]], model == "Affluent")

  text(x=0.2,y=i+3+length(varlist_general),labels=donor_row$tstat,cex=.75)
  
  # point estimate
  points(x=donor_row$estimate, y=i+3+length(varlist_general)+offset,pch=16)
  points(x=affluent_row$estimate, y=i+3+length(varlist_general)-offset, col = "GREY", pch = 18)

  segments(x0 = donor_row$LCI, y0 = i+3+length(varlist_general)+offset, x1 = donor_row$UCI, y1 = i+3+length(varlist_general)+offset)
  segments(x0 = affluent_row$LCI, y0 = i+3+length(varlist_general)-offset, x1 = affluent_row$UCI, y1 = i+3+length(varlist_general)-offset, col = "grey")
}

text(labels=rev(varlist_names),x= rep(-.4,times=length(varlist_general)),
     y=3+length(varlist_general)+seq(1,length(varlist_general)),cex=textsize,pos=4)
text(labels = "Republicans", x = -.4, y = 16,srt=90)
text(labels = "More Conservative", x = -.15, y = 4+length(varlist_general)+nrows+1,cex=.75)
text(labels = "More Liberal", x = .1, y = 4+length(varlist_general)+nrows+1,cex=.75)
text(labels = "More Conservative", x = -.15, y = 1,cex=.75)
text(labels = "More Liberal", x = .1, y = 1,cex=.75)
dev.off()


########################################
########################################
# MAIN FIGURE 2: Differences in Donor, Affluent, and General Population Policy Views on International Issues by Party
########################################
########################################

# Variable list - International Policies
varlist_globalist <- c("fa_global",
                     "i_01_rtrade", 
                     "i_01_risolation",
                     "i_01_immigration5",
                     "f_01_rdefensejoint"
)

varlist_globalist_names <- c(fa_global="Factor Score",
                             i_01_rtrade="Pro Free Trade",
                             i_01_risolation="Anti-Isolationism",
                             i_01_immigration5="Increase Immigration Limits",
                             f_01_rdefensejoint="Decrease Defense Spending")

# confirm they are in the same order!
varlist_globalist_names
varlist_globalist

# republicans
dat2a <- dat %>%
  filter(republican==1) %>%
  mutate(sample=as.factor(sample)) %>%
  mutate(sample=relevel(sample, ref="Gen Pop"))

rawdat2a <- dat2a %>%
  dplyr::select(sample,varlist_globalist) %>%  
  pivot_longer(names_to = "Variable", cols = varlist_globalist) %>%
  dplyr::select(sample,Variable,value) %>%
  drop_na()

reg2a <- rawdat2a %>%
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ sample, data = .))) %>% # run model for each variable
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(model=recode(model,
                      sampleAffluent = "Affluent",
                      sampleDonor = "Donor")) %>%
  arrange(factor(model, levels=c("Donor","Affluent"))) %>% 
  arrange(factor(term, levels=varlist_globalist))%>%
  mutate(model=factor(model, levels=c("Donor", "Affluent"))) %>%
  mutate(term=recode(term,
                     fa_global="Factor Score",
                     i_01_rtrade="Pro Free Trade",
                     i_01_risolation="Anti-Isolationism",
                     i_01_immigration5="Increase Immigration Limits",
                     f_01_rdefensejoint="Decrease Defense Spending")) %>%
  mutate(term=factor(term,levels=c("Factor Score",
                                   "Pro Free Trade",
                                   "Increase Immigration Limits",
                                   "Anti-Isolationism",
                                   "Decrease Defense Spending"))) %>%
  arrange(factor(model, levels=c("Donor","Affluent"))) %>% 
  arrange(factor(term, levels=c("Factor Score",
                                "Pro Free Trade",
                                "Increase Immigration Limits",
                                "Anti-Isolationism",
                                "Decrease Defense Spending"))) %>%
  mutate(LCI=estimate-std.error*1.96) %>%
  mutate(UCI=estimate+std.error*1.96)


diff2a <- rawdat2a %>%
  filter(sample == "Donor" | sample == "Affluent") %>%
  mutate(sample=relevel(sample, ref="Affluent")) %>% 
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ sample, data = .))) %>%
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(tstat = format(abs(round(statistic,digits=2)),nsmall=2)) %>%
  mutate(term=recode(term,
                     fa_global="Factor Score",
                     i_01_rtrade="Pro Free Trade",
                     i_01_immigration5="Increase Immigration Limits",
                     i_01_risolation="Anti-Isolationism",
                     f_01_rdefensejoint="Decrease Defense Spending")) %>%
  dplyr::select(term,tstat)

reg2a = left_join(reg2a,diff2a)

reg2a_daonly <- rawdat2a %>%
  filter(sample != "Gen Pop") %>%
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ sample, data = .))) %>% # run model for each variable
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(model=recode(model,
                      sampleDonor = "Difference")) %>%
  mutate(model=factor(model, levels=c("Donor", "Affluent"))) %>%
  mutate(term=recode(term,
                     fa_global="Factor Score",
                     i_01_rtrade="Pro Free Trade",
                     i_01_immigration5="Increase Immigration Limits",
                     i_01_risolation="Anti-Isolationism",
                     f_01_rdefensejoint="Decrease Defense Spending")) %>%
  mutate(term=factor(term,levels=c("Factor Score",
                                   "Pro Free Trade",
                                   "Increase Immigration Limits",
                                   "Anti-Isolationism",
                                   "Decrease Defense Spending"))) %>%
  arrange(factor(term, levels=c("Factor Score",
                                "Pro Free Trade",
                                "Increase Immigration Limits",
                                "Anti-Isolationism",
                                "Decrease Defense Spending"))) %>%
  mutate(LCI=estimate-std.error*1.96) %>%
  mutate(UCI=estimate+std.error*1.96)

# democrats

dat2b <- dat %>%
  filter(democrat==1) %>%
  mutate(sample=as.factor(sample)) %>%
  mutate(sample=relevel(sample, ref="Gen Pop"))

rawdat2b <- dat2b %>%
  dplyr::select(sample,varlist_globalist) %>%  
  pivot_longer(names_to = "Variable", cols = varlist_globalist) %>%
  dplyr::select(sample,Variable,value) %>%
  drop_na()

reg2b <- rawdat2b %>%
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ sample, data = .))) %>% # run model for each variable
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(model=recode(model,
                      sampleAffluent = "Affluent",
                      sampleDonor = "Donor")) %>%
  arrange(factor(model, levels=c("Donor","Affluent"))) %>% 
  arrange(factor(term, levels=varlist_globalist))%>%
  mutate(model=factor(model, levels=c("Donor", "Affluent"))) %>%
  mutate(term=recode(term,
                     fa_global="Factor Score",
                     i_01_rtrade="Pro Free Trade",
                     i_01_risolation="Anti-Isolationism",
                     i_01_immigration5="Increase Immigration Limits",
                     f_01_rdefensejoint="Decrease Defense Spending")) %>%
  mutate(term=factor(term,levels=c("Factor Score",
                                      "Pro Free Trade",
                                      "Increase Immigration Limits",
                                      "Anti-Isolationism",
                                      "Decrease Defense Spending"))) %>%
  arrange(factor(model, levels=c("Donor","Affluent"))) %>% 
  arrange(factor(term, levels=c("Factor Score",
                                "Pro Free Trade",
                                "Increase Immigration Limits",
                                "Anti-Isolationism",
                                "Decrease Defense Spending"))) %>%
  mutate(LCI=estimate-std.error*1.96) %>%
  mutate(UCI=estimate+std.error*1.96)

diff2b <- rawdat2b %>%
  filter(sample == "Donor" | sample == "Affluent") %>%
  mutate(sample=relevel(sample, ref="Affluent")) %>% 
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ sample, data = .))) %>%
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(tstat = format(abs(round(statistic,digits=2)),nsmall=2)) %>%
  mutate(term=recode(term,
                     fa_global="Factor Score",
                     i_01_rtrade="Pro Free Trade",
                     i_01_immigration5="Increase Immigration Limits",
                     i_01_risolation="Anti-Isolationism",
                     f_01_rdefensejoint="Decrease Defense Spending")) %>%
  dplyr::select(term,tstat)

reg2b = left_join(reg2b,diff2b)

reg2b_daonly <- rawdat2b %>%
  filter(sample != "Gen Pop") %>%
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ sample, data = .))) %>% # run model for each variable
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(model=recode(model,
                      sampleDonor = "Difference")) %>%
  mutate(model=factor(model, levels=c("Donor", "Affluent"))) %>%
  mutate(term=recode(term,
                     fa_global="Factor Score",
                     i_01_rtrade="Pro Free Trade",
                     i_01_immigration5="Increase Immigration Limits",
                     i_01_risolation="Anti-Isolationism",
                     f_01_rdefensejoint="Decrease Defense Spending")) %>%
  mutate(term=factor(term,levels=c("Factor Score",
                                   "Pro Free Trade",
                                   "Increase Immigration Limits",
                                   "Anti-Isolationism",
                                   "Decrease Defense Spending"))) %>%
  arrange(factor(term, levels=c("Factor Score",
                                "Pro Free Trade",
                                "Increase Immigration Limits",
                                "Anti-Isolationism",
                                "Decrease Defense Spending"))) %>%
  mutate(LCI=estimate-std.error*1.96) %>%
  mutate(UCI=estimate+std.error*1.96)

nrows <- length(varlist_globalist)
offset <- .2

pdf(file="~/Desktop/jop replication/MAIN_Figure2.pdf")

plot(x=c(-.5,.3),y=c(1,2*length(varlist_globalist)+4),type="n",axes=FALSE,
     xlab="Difference from Copartisan \n  General Population Mean (and 95% CI)",
     ylab="",
     main = "Average Policy Differences \n Among Donors, Affluent, and General Public")
abline(v=seq(-.3,.3,by=.05),lty=2,col="light grey")
abline(v=0)
axis(1,at=seq(-.3,.3,by=.1),
     labels=c(-.3,-.2,-.1,0,.1,.2,.3))

# democrats
for(i in 1: length(varlist_globalist)){
  donor_row <- reg2b %>%
    filter(term == varlist_globalist_names[varlist_globalist[nrows-i+1]], model == "Donor")
  affluent_row <- reg2b %>%
    filter(term == varlist_globalist_names[varlist_globalist[nrows-i+1]], model == "Affluent")
  
  text(x=0.29,y=i+1,labels=donor_row$tstat,cex=.75)
  
  # point estimate
  points(x=donor_row$estimate, y=i+1+offset,pch=16)
  points(x=affluent_row$estimate, y=i+1-offset, col = "GREY", pch = 18)
  
  segments(x0 = donor_row$LCI, y0 = i+1+offset, x1 = donor_row$UCI, y1 = i+1+offset)
  segments(x0 = affluent_row$LCI, y0 = i+1-offset, x1 = affluent_row$UCI, y1 = i+1-offset, col = "grey")
}

text(labels=rev(varlist_globalist_names),x=rep(-.4,times=length(varlist_globalist)),
     y=1+seq(1,length(varlist_globalist)),cex=textsize,pos=4)
text(labels = "Democrats", x = -.4, y = 4,srt=90)

legend(.1,8.5, legend=c("Donors", "Affluent"), col=c("black","light grey"), pch=c(16,18),cex=.75)

# republicans
for(i in 1: length(varlist_globalist)){
  donor_row <- reg2a %>%
    filter(term == varlist_globalist_names[varlist_globalist[nrows-i+1]], model == "Donor")
  affluent_row <- reg2a %>%
    filter(term == varlist_globalist_names[varlist_globalist[nrows-i+1]], model == "Affluent")
  
  text(x=0.29,y=i+3+length(varlist_globalist),labels=donor_row$tstat,cex=.75)
  
  # point estimate
  points(x=donor_row$estimate, y=i+3+length(varlist_globalist)+offset,pch=16)
  points(x=affluent_row$estimate, y=i+3+length(varlist_globalist)-offset, col = "GREY", pch = 18)
  
  segments(x0 = donor_row$LCI, y0 = i+3+length(varlist_globalist)+offset, x1 = donor_row$UCI, y1 = i+3+length(varlist_globalist)+offset)
  segments(x0 = affluent_row$LCI, y0 = i+3+length(varlist_globalist)-offset, x1 = affluent_row$UCI, y1 = i+3+length(varlist_globalist)-offset, col = "grey")
}

text(labels=rev(varlist_globalist_names),x= rep(-.4,times=length(varlist_globalist)),
     y=3+length(varlist_globalist)+seq(1,length(varlist_globalist)),cex=textsize,pos=4)
text(labels = "Republicans", x = -.4, y = 11,srt=90)
text(labels = "Less Internationalist", x = -.15, y = 3+length(varlist_globalist)+nrows+1,cex=.75)
text(labels = "More Internationalist", x = .1, y = 3+length(varlist_globalist)+nrows+1,cex=.75)
text(labels = "Less Internationalist", x = -.15, y = 1,cex=.75)
text(labels = "More Internationalist", x = .1, y = 1,cex=.75)
dev.off()

##################################
##################################
# MAIN FIGURE 3: Difference in Policy Views by Donor and Affluence Status on Domestic and International Issues by Party
##################################
##################################

dat <- dat %>%
  mutate(split = ifelse(AffluentDonor==1,"AffluentDonor","Gen Pop"),
         split = ifelse(NonAffluentDonor==1,"NonAffluentDonor",split),
         split = ifelse(AffluentNonDonor==1,"AffluentNonDonor",split),
         split = ifelse(sample==3,"Gen Pop",split))

#############
# Domestic
#############

# Republicans

dat3a <- dat %>%
  filter(republican==1) %>%
  mutate(split=as.factor(split)) %>%
  mutate(split=relevel(split, ref="Gen Pop"))

rawdat3a <- dat3a %>%
  select(split,varlist_general) %>%  
  pivot_longer(names_to = "Variable", cols = varlist_general) %>%
  select(split,Variable,value) %>%
  drop_na()

reg3a <- rawdat3a %>%
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ split, data = .))) %>% # run model for each variable
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(model=recode(model,
                      splitAffluentDonor = "Affluent Donor",
                      splitNonAffluentDonor = "Non-Affluent Donor",
                      splitAffluentNonDonor = "Affluent Non-Donor")) %>%
  arrange(factor(model, levels=c("Affluent Donor","Non-Affluent Donor", "Affluent Non-Donor"))) %>% 
  arrange(factor(term, levels=varlist_general))%>%
  mutate(term=recode(term,
                     fa_all="Factor Score",
                     f_01_minwagejoint="Increase Minimum Wage",
                     i_01_taxes1="Incr. Top Marginal Tax Rate",
                     f_01_tanfjoint="Increase TANF Spending",
                     f_01_sumenvironment="Pro Environmentalism",
                     i_01_health3="Incr. Govt Role in Health Care",
                     f_01_abortionjoint="Fewer Abortion Restrictions",
                     i_01_rguncontrol="More Gun Control")) %>%
  mutate(LCI=estimate-std.error*1.96) %>%
  mutate(UCI=estimate+std.error*1.96)


# Democrats

dat3b <- dat %>%
  filter(democrat==1) %>%
  mutate(split=as.factor(split)) %>%
  mutate(split=relevel(split, ref="Gen Pop"))

rawdat3b <- dat3b %>%
  select(split,varlist_general) %>%  
  pivot_longer(names_to = "Variable", cols = varlist_general) %>%
  select(split,Variable,value) %>%
  drop_na()

reg3b <- rawdat3b %>%
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ split, data = .))) %>% # run model for each variable
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(model=recode(model,
                      splitAffluentDonor = "Affluent Donor",
                      splitNonAffluentDonor = "Non-Affluent Donor",
                      splitAffluentNonDonor = "Affluent Non-Donor")) %>%
  arrange(factor(model, levels=c("Affluent Donor","Non-Affluent Donor", "Affluent Non-Donor"))) %>% 
  arrange(factor(term, levels=varlist_general))%>%
  mutate(term=recode(term,
                     fa_all="Factor Score",
                     f_01_minwagejoint="Increase Minimum Wage",
                     i_01_taxes1="Incr. Top Marginal Tax Rate",
                     f_01_tanfjoint="Increase TANF Spending",
                     f_01_sumenvironment="Pro Environmentalism",
                     i_01_health3="Incr. Govt Role in Health Care",
                     f_01_abortionjoint="Fewer Abortion Restrictions",
                     i_01_rguncontrol="More Gun Control")) %>%
  mutate(LCI=estimate-std.error*1.96) %>%
  mutate(UCI=estimate+std.error*1.96)


#######################################################
# International
#######################################################

# Republicans

dat4a <- dat %>%
  filter(republican==1) %>%
  mutate(split=as.factor(split)) %>%
  mutate(split=relevel(split, ref="Gen Pop"))

rawdat4a <- dat4a %>%
  select(split,varlist_globalist) %>%  
  pivot_longer(names_to = "Variable", cols = varlist_globalist) %>%
  select(split,Variable,value) %>%
  drop_na()

reg4a <- rawdat4a %>%
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ split, data = .))) %>% # run model for each variable
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(model=recode(model,
                      splitAffluentDonor = "Affluent Donor",
                      splitNonAffluentDonor = "Non-Affluent Donor",
                      splitAffluentNonDonor = "Affluent Non-Donor")) %>%
  arrange(factor(model, levels=c("Affluent Donor","Non-Affluent Donor", "Affluent Non-Donor"))) %>% 
  arrange(factor(term, levels=varlist_globalist))%>%
  mutate(term=recode(term,
                     fa_global="Factor Score",
                     i_01_rtrade="Pro Free Trade",
                     i_01_immigration5="Increase Immigration Limits",
                     i_01_risolation="Anti-Isolationism",
                     f_01_rdefensejoint="Decrease Defense Spending")) %>%
  mutate(LCI=estimate-std.error*1.96) %>%
  mutate(UCI=estimate+std.error*1.96)

dat4b <- dat %>%
  filter(democrat==1) %>%
  mutate(split=as.factor(split)) %>%
  mutate(split=relevel(split, ref="Gen Pop")) 

rawdat4b <- dat4b %>%
  select(split,varlist_globalist) %>%  
  pivot_longer(names_to = "Variable", cols = varlist_globalist) %>%
  select(split,Variable,value) %>%
  drop_na()

reg4b <- rawdat4b %>%
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ split, data = .))) %>% # run model for each variable
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(model=recode(model,
                      splitAffluentDonor = "Affluent Donor",
                      splitNonAffluentDonor = "Non-Affluent Donor",
                      splitAffluentNonDonor = "Affluent Non-Donor")) %>%
  arrange(factor(model, levels=c("Affluent Donor","Non-Affluent Donor", "Affluent Non-Donor"))) %>% 
  arrange(factor(term, levels=varlist_globalist))%>%
  mutate(term=recode(term,
                     fa_global="Factor Score",
                     i_01_rtrade="Pro Free Trade",
                     i_01_immigration5="Increase Immigration Limits",
                     i_01_risolation="Anti-Isolationism",
                     f_01_rdefensejoint="Decrease Defense Spending")) %>%
  mutate(LCI=estimate-std.error*1.96) %>%
  mutate(UCI=estimate+std.error*1.96)

nrows <- length(varlist_globalist)
offset <- .2

##########################################################################################################################
# MAIN TABLE 1: Pairwise Difference of Means by Donor and Affluence Status
##########################################################################################################################

# Affluent Donor vs. Non Affluent Donor
# Rep Domestic
rawdat3a %>%
  mutate(split=relevel(split, ref="AffluentDonor")) %>% 
  filter(split == "AffluentDonor" | split == "NonAffluentDonor") %>%
  filter(Variable == "fa_all") %>%
  do(broom::tidy(lm(value ~ split, data = .)))

# Rep Intl
rawdat4a %>%
  mutate(split=relevel(split, ref="AffluentDonor")) %>% 
  filter(split == "AffluentDonor" | split == "NonAffluentDonor") %>%
  filter(Variable == "fa_global") %>%
  do(broom::tidy(lm(value ~ split, data = .)))

# Democrats
rawdat3b %>%
  mutate(split=relevel(split, ref="AffluentDonor")) %>% 
  filter(split == "AffluentDonor" | split == "NonAffluentDonor") %>%
  filter(Variable == "fa_all") %>%
  do(broom::tidy(lm(value ~ split, data = .)))

rawdat4b %>%
  mutate(split=relevel(split, ref="AffluentDonor")) %>% 
  filter(split == "AffluentDonor" | split == "NonAffluentDonor") %>%
  filter(Variable == "fa_global") %>%
  do(broom::tidy(lm(value ~ split, data = .)))

# Non Affluent Donor vs. Affluent Non-Donor
# Rep Domestic
rawdat3a %>%
  mutate(split=relevel(split, ref="AffluentNonDonor")) %>% 
  filter(split == "NonAffluentDonor" | split == "AffluentNonDonor") %>%
  filter(Variable == "fa_all") %>%
  do(broom::tidy(lm(value ~ split, data = .)))

# Rep Intl
rawdat4a %>%
  mutate(split=relevel(split, ref="AffluentNonDonor")) %>% 
  filter(split == "NonAffluentDonor" | split == "AffluentNonDonor") %>%
  filter(Variable == "fa_global") %>%
  do(broom::tidy(lm(value ~ split, data = .)))

# Democrats
rawdat3b %>%
  mutate(split=relevel(split, ref="AffluentNonDonor")) %>% 
  filter(split == "NonAffluentDonor" | split == "AffluentNonDonor") %>%
  filter(Variable == "fa_all") %>%
  do(broom::tidy(lm(value ~ split, data = .)))

rawdat4b %>%
  mutate(split=relevel(split, ref="AffluentNonDonor")) %>% 
  filter(split == "NonAffluentDonor" | split == "AffluentNonDonor") %>%
  filter(Variable == "fa_global") %>%
  do(broom::tidy(lm(value ~ split, data = .)))

# Affluent Donor vs. Affluent Non-Donor
# Rep Domestic
rawdat3a %>%
  mutate(split=relevel(split, ref="AffluentNonDonor")) %>% 
  filter(split == "AffluentDonor" | split == "AffluentNonDonor") %>%
  filter(Variable == "fa_all") %>%
  do(broom::tidy(lm(value ~ split, data = .)))

# Rep Intl
rawdat4a %>%
  mutate(split=relevel(split, ref="AffluentNonDonor")) %>% 
  filter(split == "AffluentDonor" | split == "AffluentNonDonor") %>%
  filter(Variable == "fa_global") %>%
  do(broom::tidy(lm(value ~ split, data = .)))

# Democrats
rawdat3b %>%
  mutate(split=relevel(split, ref="AffluentNonDonor")) %>% 
  filter(split == "AffluentDonor" | split == "AffluentNonDonor") %>%
  filter(Variable == "fa_all") %>%
  do(broom::tidy(lm(value ~ split, data = .)))

rawdat4b %>%
  mutate(split=relevel(split, ref="AffluentNonDonor")) %>% 
  filter(split == "AffluentDonor" | split == "AffluentNonDonor") %>%
  filter(Variable == "fa_global") %>%
  do(broom::tidy(lm(value ~ split, data = .)))


#############################################################
#       CREATE FIGURE 3 PLOT
#############################################################

reg3a_fs = reg3a %>%
  filter(term=="Factor Score") %>%
  mutate(Party = "Republicans",
         Issues = "Domestic Policy")

reg3a_fs <- bind_rows(reg3a_fs[1,],reg3a_fs[3,],reg3a_fs[2,])

reg3b_fs = reg3b %>%
  filter(term=="Factor Score") %>%
  mutate(Party = "Democrats",
         Issues = "Domestic Policy")

reg3b_fs <- bind_rows(reg3b_fs[1,],reg3b_fs[3,],reg3b_fs[2,])

reg4a_fs = reg4a %>%
  filter(term=="Factor Score") %>%
  mutate(Party = "Republicans",
         Issues = "International")

reg4a_fs <- bind_rows(reg4a_fs[1,],reg4a_fs[3,],reg4a_fs[2,])

reg4b_fs = reg4b %>%
  filter(term=="Factor Score") %>%
  mutate(Party = "Democrats",
         Issues = "International")

reg4b_fs <- bind_rows(reg4b_fs[1,],reg4b_fs[3,],reg4b_fs[2,])

rg_fs = bind_rows(reg4b_fs,reg3b_fs,reg4a_fs,reg3a_fs)

# order 
rg_fs = rg_fs %>%
  mutate(model=factor(model, levels=c("Non-Affluent Donor","Affluent Donor","Affluent Non-Donor"))) %>%
  mutate(Party=factor(Party, levels=c("Republicans", "Democrats"))) %>%
  mutate(Issues=factor(Issues, levels=c("Domestic Policy", "International"))) %>%
  arrange(Party, Issues, model)
yindx <- rev(c(.8,1,1.2,1.8,2,2.2,2.8,3,3.2,3.8,4,4.2))

rg_fs = rg_fs %>%
  mutate(col = if_else(model == "Affluent Non-Donor","GREY","BLACK"),
         plotchar = if_else(model == "Affluent Non-Donor",18,15),
         plotchar = if_else(model == "Affluent Donor",16,plotchar))

pdf("~/Desktop/jop replication/MAIN_Figure3.pdf")

plot(x=c(-.5,.3),y=c(0,5),type="n",axes=FALSE,
     xlab="Difference from Copartisan \n  General Population (and 95% CI)",
     ylab="",
     main = "Average Policy Differences By Giving and Affluence")
abline(v=seq(-.3,.3,by=.05),lty=2,col="light grey")
abline(v=0)
axis(1,at=seq(-.3,.3,by=.1),
     labels=c(-.3,-.2,-.1,0,.1,.2,.3))

for(i in 1:nrow(rg_fs)){
  points(x=rg_fs$estimate[i], y=yindx[i],col = rg_fs$col[i], pch=rg_fs$plotchar[i])
  segments(x0 = rg_fs$LCI[i], y0 = yindx[i], x1 = rg_fs$UCI[i], y1 = yindx[i])
}

text(x=-.35,y=1,"International")
text(x=-.35,y=2,"Domestic")
text(x=-.35,y=4,"Domestic")
text(x=-.35,y=3,"International")

text(labels = "More Liberal \n or More Internationalist", x = .2, y = .1,cex=.75)
text(labels = "More Conservative \n or Less Internationalist", x = -.2, y = .1,cex=.75)
text(labels = "More Liberal \n or More Internationalist", x = .2, y = 5,cex=.75)
text(labels = "More Conservative \n or Less Internationalist", x = -.2, y = 5,cex=.75)

text(labels = "Republicans", x = -.45, y = 3.5,srt=90)
text(labels = "Democrats", x = -.45, y = 1.5,srt=90)

legend(-.3,2.75, legend=c("Non-Affluent Donors","Affluent Donors", "Affluent Non-Donors"), 
       col=c("black","black","light grey"), 
       pch=c(15,16,18),
       cex=.7)

dev.off()


##################################
# MAIN TABLE 2: Donor and Affluent Policy Divergence, with Controls
##################################

# domestic
# democrats
reg_t1_domestic_democrat <- dat %>% 
  filter(sample!="Gen Pop") %>%
  filter(democrat==1) %>%
  lm(fa_all ~ valdonor + d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age, data=.)
# republicans
reg_t1_domestic_republican <- dat %>% 
  filter(sample!="Gen Pop") %>%
  filter(republican==1) %>%
  lm(fa_all ~ valdonor + d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age, data=.)

# international
# democrats
reg_t1_global_democrat <- dat %>% 
  filter(sample!="Gen Pop") %>%
  filter(democrat==1) %>%
  lm(fa_global ~ valdonor + d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age, data=.)
# republicans
reg_t1_global_republican <- dat %>% 
  filter(sample!="Gen Pop") %>%
  filter(republican==1) %>%
  lm(fa_global ~ valdonor + d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age, data=.)

r1 <- reg_t1_domestic_democrat
r2 <- reg_t1_domestic_republican
r3 <- reg_t1_global_democrat
r4 <- reg_t1_global_republican

stargazer(r1, r2,
          r3, r4,
          type="html",out = paste(outdir_tables,"Main_Table2.html", sep=""),
          column.labels=c("Democrat","Republican","Democrat","Republican"),
          dep.var.labels = c("Domestic", "International"),
          dep.var.caption="",
          covariate.labels=c("Validated Donor",
                             "Income [1,10]",
                             "Net Worth [1,7]",
                             "High political interest",
                             "Religion very important",
                             "Postgraduate degree",
                             "High School or less",
                             "Union Member",
                             "Female",
                             "Black",
                             "Latino/a",
                             "AAPI",
                             "Age")
)



##################################
# MAIN TABLE 3: Donor and Affluent Policy Divergence, with interactions
##################################

# domestic
# democrats
reg_t2_domestic_democrat <- dat %>% 
  filter(sample!="Gen Pop") %>%
  filter(democrat==1) %>%
  lm(fa_all ~ valdonor + smallamtcont + outstate + pres +
       d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age, data=.)
# republicans
reg_t2_domestic_republican <- dat %>% 
  filter(sample!="Gen Pop") %>%
  filter(republican==1) %>%
  lm(fa_all ~ valdonor + smallamtcont + outstate + pres +
       d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age, data=.)
# international
# democrats
reg_t2_global_democrat <- dat %>% 
  filter(sample!="Gen Pop") %>%
  filter(democrat==1) %>%
  lm(fa_global ~ valdonor + smallamtcont + outstate + pres +
       d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age, data=.)
# republicans
reg_t2_global_republican <- dat %>% 
  filter(sample!="Gen Pop") %>%
  filter(republican==1) %>%
  lm(fa_global ~ valdonor + smallamtcont + outstate + pres +
       d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age, data=.)

r1 <- reg_t2_domestic_democrat
r2 <- reg_t2_domestic_republican
r3 <- reg_t2_global_democrat
r4 <- reg_t2_global_republican


stargazer(r1, r2,
          r3, r4,
          type="html",out=paste(outdir_tables,"Main_Table3.html",sep=""),
          column.labels=c("Democrat","Republican","Democrat","Republican"),
          dep.var.labels = c("Domestic", "International"),
          dep.var.caption="",
          keep = c("valdonor", "smallamtcont", "outstate", "pres"),
          covariate.labels=c("Validated Donor",
                             "Gave $200 or less",
                             "Gave out-of-state",
                             "Gave to 2016 presidential contest")
)



############################################################################################
############################################################################################
# APPENDIX A
############################################################################################
############################################################################################

# Use Inverse Propensity score for weights
# Drop data with missing weights (i.e., missing voter file demographics (but we coded missing as a category in weighting))
dat_wt <- dat %>%
  drop_na(invpropensitywgt)

# Variable list - General Policies - must be in same order!
varlist_general <- c("fa_all",
                     "f_01_minwagejoint", 
                     "i_01_taxes1",
                     "f_01_tanfjoint",
                     "f_01_sumenvironment",
                     "i_01_health3",
                     "f_01_abortionjoint",
                     "i_01_rguncontrol"
)
varlist_names <- c(fa_all="Factor Score",
                   f_01_minwagejoint="Increase Minimum Wage",
                   i_01_taxes1="Incr. Top Marginal Tax Rate",
                   f_01_tanfjoint="Increase TANF Spending",
                   f_01_sumenvironment="Pro Environmentalism",
                   i_01_health3="Incr. Govt Role in Health Care",
                   f_01_abortionjoint="Fewer Abortion Restrictions",
                   i_01_rguncontrol="More Gun Control")

textsize <- .6

############################################################################################################################################################################
# Figure A1. Figure 1 Replication with Respondent Weights
############################################################################################################################################################################

dat1a_wt <- dat_wt %>%
  filter(republican==1) %>%
  mutate(sample=as.factor(sample)) %>%
  mutate(sample=relevel(sample, ref="Gen Pop"))

rawdat1a_wt <- dat1a_wt %>%
  select(sample,varlist_general,invpropensitywgt) %>%  
  pivot_longer(names_to = "Variable", cols = varlist_general) %>%
  select(sample,Variable,invpropensitywgt,value) %>%
  drop_na()

reg1a_wt <- rawdat1a_wt %>%
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ sample, data = ., weights=invpropensitywgt))) %>% # run model for each variable
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(model=recode(model,
                      sampleAffluent = "Affluent",
                      sampleDonor = "Donor")) %>%
  arrange(factor(model, levels=c("Donor","Affluent"))) %>% 
  arrange(factor(term, levels=varlist_general))%>%
  mutate(model=factor(model, levels=c("Donor", "Affluent"))) %>%
  mutate(term=recode(term,
                     fa_all="Factor Score",
                     f_01_minwagejoint="Increase Minimum Wage",
                     i_01_taxes1="Incr. Top Marginal Tax Rate",
                     f_01_tanfjoint="Increase TANF Spending",
                     f_01_sumenvironment="Pro Environmentalism",
                     i_01_health3="Incr. Govt Role in Health Care",
                     f_01_abortionjoint="Fewer Abortion Restrictions",
                     i_01_rguncontrol="More Gun Control")) %>%
  mutate(term=factor(term, levels=c("Factor Score", 
                                    "Increase Minimum Wage",
                                    "Incr. Top Marginal Tax Rate",
                                    "Increase TANF Spending",
                                    "Pro Environmentalism",
                                    "Incr. Govt Role in Health Care",
                                    "Fewer Abortion Restrictions",
                                    "More Gun Control"))) %>%
  mutate(LCI=estimate-std.error*1.96) %>%
  mutate(UCI=estimate+std.error*1.96)

# Democrats Regression
dat1b_wt <- dat_wt %>%
  filter(democrat==1) %>%
  mutate(sample=as.factor(sample)) %>%
  mutate(sample=relevel(sample, ref="Gen Pop"))

rawdat1b_wt <- dat1b_wt %>%
  select(sample,varlist_general,invpropensitywgt) %>%  
  pivot_longer(names_to = "Variable", cols = varlist_general) %>%
  select(sample,Variable,invpropensitywgt,value) %>%
  drop_na()

reg1b_wt <- rawdat1b_wt %>%
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ sample, data = ., weights=invpropensitywgt))) %>% # run model for each variable
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(model=recode(model,
                      sampleAffluent = "Affluent",
                      sampleDonor = "Donor")) %>%
  arrange(factor(model, levels=c("Donor","Affluent"))) %>% 
  arrange(factor(term, levels=varlist_general))%>%
  mutate(model=factor(model, levels=c("Donor", "Affluent"))) %>%
  mutate(term=recode(term,
                     fa_all="Factor Score",
                     f_01_minwagejoint="Increase Minimum Wage",
                     i_01_taxes1="Incr. Top Marginal Tax Rate",
                     f_01_tanfjoint="Increase TANF Spending",
                     f_01_sumenvironment="Pro Environmentalism",
                     i_01_health3="Incr. Govt Role in Health Care",
                     f_01_abortionjoint="Fewer Abortion Restrictions",
                     i_01_rguncontrol="More Gun Control")) %>%
  mutate(term=factor(term, levels=c("Factor Score", 
                                    "Increase Minimum Wage",
                                    "Incr. Top Marginal Tax Rate",
                                    "Increase TANF Spending",
                                    "Pro Environmentalism",
                                    "Incr. Govt Role in Health Care",
                                    "Fewer Abortion Restrictions",
                                    "More Gun Control"))) %>%
  mutate(LCI=estimate-std.error*1.96) %>%
  mutate(UCI=estimate+std.error*1.96)

nrows <- length(varlist_general)
offset <- .2

pdf(file=paste(outdir_figures,"SI_FigureA1_Figure1_weighted.pdf", sep=""))

plot(x=c(-.4,.25),y=c(1,2*length(varlist_general)+5),type="n",axes=FALSE,
     xlab="Difference from Copartisan \n  General Population Mean (and 95% CI)",
     ylab="",
     main = "Average Policy Differences \n Among Donors, Affluent, and General Public")
abline(v=seq(-.3,.15,by=.05),lty=2,col="light grey")
abline(v=0)
axis(1,at=seq(-.3,.2,by=.05),
     labels=c(-.3,-.25,-.2,-.15,-.1,-.05,0,.05,.1,.15,.2))

# democrats
for(i in 1: length(varlist_general)){
  donor_row <- reg1b_wt %>%
    filter(term == varlist_names[varlist_general[nrows-i+1]], model == "Donor")
  affluent_row <- reg1b_wt %>%
    filter(term == varlist_names[varlist_general[nrows-i+1]], model == "Affluent")
  
  # point estimate
  points(x=donor_row$estimate, y=i+1+offset,pch=16)
  points(x=affluent_row$estimate, y=i+1-offset, col = "GREY", pch = 18)
  
  segments(x0 = donor_row$LCI, y0 = i+1+offset, x1 = donor_row$UCI, y1 = i+1+offset)
  segments(x0 = affluent_row$LCI, y0 = i+1-offset, x1 = affluent_row$UCI, y1 = i+1-offset, col = "grey")
}

text(labels=rev(varlist_names),x=rep(-.4,times=length(varlist_general)),
     y=1+seq(1,length(varlist_general)),cex=textsize,pos=4)
text(labels = "Democrats", x = -.4, y = 5.5,srt=90)

legend(.1,13, legend=c("Donors", "Affluent"), col=c("black","light grey"), pch=c(16,18),cex=.75)

# republicans
for(i in 1: length(varlist_general)){
  donor_row <- reg1a_wt %>%
    filter(term == varlist_names[varlist_general[nrows-i+1]], model == "Donor")
  affluent_row <- reg1a_wt %>%
    filter(term == varlist_names[varlist_general[nrows-i+1]], model == "Affluent")
  
  # point estimate
  points(x=donor_row$estimate, y=i+3+length(varlist_general)+offset,pch=16)
  points(x=affluent_row$estimate, y=i+3+length(varlist_general)-offset, col = "GREY", pch = 18)
  
  segments(x0 = donor_row$LCI, y0 = i+3+length(varlist_general)+offset, x1 = donor_row$UCI, y1 = i+3+length(varlist_general)+offset)
  segments(x0 = affluent_row$LCI, y0 = i+3+length(varlist_general)-offset, x1 = affluent_row$UCI, y1 = i+3+length(varlist_general)-offset, col = "grey")
}

text(labels=rev(varlist_names),x= rep(-.4,times=length(varlist_general)),
     y=3+length(varlist_general)+seq(1,length(varlist_general)),cex=textsize,pos=4)
text(labels = "Republicans", x = -.4, y = 16,srt=90)
text(labels = "More Conservative", x = -.15, y = 4+length(varlist_general)+nrows+1,cex=.75)
text(labels = "More Liberal", x = .1, y = 4+length(varlist_general)+nrows+1,cex=.75)
text(labels = "More Conservative", x = -.15, y = 1,cex=.75)
text(labels = "More Liberal", x = .1, y = 1,cex=.75)
dev.off()

############################################################################################################################################################################
# Table A1. Domestic Issues Difference of Means Comparisons by Sample with Weights (Figure A1).
############################################################################################################################################################################

reg1a_wt$Party <- "Republicans"
reg1b_wt$Party <- "Democrats"
reg1_wt <- rbind(reg1a_wt, reg1b_wt)
reg1_wt <- reg1_wt %>%
  rename(Issue=term,
         Group=model,
         Estimate=estimate,
         `Standard Error`=std.error) %>%
  select(Party, Issue, Group, Estimate, `Standard Error`)

reg1_wt <- as.data.frame(reg1_wt) %>%
  arrange(Group, Issue, Party)

reg1_wt$`Standard Error` = paste0("(",sprintf(reg1_wt$`Standard Error`, fmt="%.3f"),")")
reg1_wt$Estimate = sprintf(reg1_wt$Estimate, fmt="%.3f")

reg1_wt_ <- reg1_wt %>%
  pivot_longer(cols=c("Estimate", "Standard Error")) %>%
  pivot_wider(names_from=c("Group","Party"))


reg1_wt_$Issue = as.character(reg1_wt_$Issue)
reg1_wt_$Issue[reg1_wt_$name=="Standard Error"] = ""

reg1_wt_ <- reg1_wt_ %>%
  select("Issue", "Donor_Democrats", "Donor_Republicans", "Affluent_Democrats", "Affluent_Republicans")

kbl(reg1_wt_, "html", 
    col.names = c("", "Democrats", 
                  "Republicans", "Democrats", "Republicans")) %>%
  kable_classic(full_width=F, html_font="Cambria") %>%
  add_header_above(c(" " = 1, "Donors" = 2, "Affluent" = 2)) %>%
  cat(., file=paste(outdir_tables, "SI_TableA1_figure_A1_weighted.html", sep=""))


##############################################################################################################
##############################################################################################################
# SI FIGURE 2 International 
##############################################################################################################
##############################################################################################################

# Variable list - Globalist Policies
varlist_globalist <- c("fa_global",
                       "i_01_rtrade", 
                       "i_01_risolation",
                       "i_01_immigration5",
                       "f_01_rdefensejoint"
)

varlist_globalist_names <- c(fa_global="Factor Score",
                             i_01_rtrade="Pro Free Trade",
                             i_01_risolation="Anti-Isolationism",
                             i_01_immigration5="Increase Immigration Limits",
                             f_01_rdefensejoint="Decrease Defense Spending")

# confirm they are in the same order!
varlist_globalist_names
varlist_globalist

############################################################################################################################################################################
# Figure A2. Figure 2 Replication with Respondent Weights
############################################################################################################################################################################

# republicans
dat2a_wt <- dat_wt %>%
  filter(republican==1) %>%
  mutate(sample=as.factor(sample)) %>%
  mutate(sample=relevel(sample, ref="Gen Pop"))

rawdat2a_wt <- dat2a_wt %>%
  select(sample,varlist_globalist,invpropensitywgt) %>%  
  pivot_longer(names_to = "Variable", cols = varlist_globalist) %>%
  select(sample,Variable,invpropensitywgt,value) %>%
  drop_na()

reg2a_wt <- rawdat2a_wt %>%
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ sample, data = ., weights=invpropensitywgt))) %>% # run model for each variable
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(model=recode(model,
                      sampleAffluent = "Affluent",
                      sampleDonor = "Donor")) %>%
  mutate(model=factor(model, levels=c("Donor", "Affluent"))) %>%
  mutate(term=recode(term,
                     fa_global="Factor Score",
                     i_01_rtrade="Pro Free Trade",
                     i_01_immigration5="Increase Immigration Limits",
                     i_01_risolation="Anti-Isolationism",
                     f_01_rdefensejoint="Decrease Defense Spending")) %>%
  mutate(term=factor(term,levels=c("Factor Score",
                                   "Pro Free Trade",
                                   "Increase Immigration Limits",
                                   "Anti-Isolationism",
                                   "Decrease Defense Spending"))) %>%
  arrange(factor(model, levels=c("Donor","Affluent"))) %>% 
  arrange(factor(term, levels=c("Factor Score",
                                "Pro Free Trade",
                                "Increase Immigration Limits",
                                "Anti-Isolationism",
                                "Decrease Defense Spending"))) %>%
  mutate(LCI=estimate-std.error*1.96) %>%
  mutate(UCI=estimate+std.error*1.96)

# democrats

dat2b_wt <- dat_wt %>%
  filter(democrat==1) %>%
  mutate(sample=as.factor(sample)) %>%
  mutate(sample=relevel(sample, ref="Gen Pop"))

rawdat2b_wt <- dat2b_wt %>%
  select(sample,varlist_globalist,invpropensitywgt) %>%  
  pivot_longer(names_to = "Variable", cols = varlist_globalist) %>%
  select(sample,Variable,invpropensitywgt,value) %>%
  drop_na()

reg2b_wt <- rawdat2b_wt %>%
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ sample, data = ., weights=invpropensitywgt))) %>% # run model for each variable
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(model=recode(model,
                      sampleAffluent = "Affluent",
                      sampleDonor = "Donor")) %>%
  arrange(factor(model, levels=c("Donor","Affluent"))) %>% 
  arrange(factor(term, levels=varlist_general))%>%
  mutate(model=factor(model, levels=c("Donor", "Affluent"))) %>%
  mutate(term=recode(term,
                     fa_global="Factor Score",
                     i_01_rtrade="Pro Free Trade",
                     i_01_risolation="Anti-Isolationism",
                     i_01_immigration5="Increase Immigration Limits",
                     f_01_rdefensejoint="Decrease Defense Spending")) %>%
  mutate(term=factor(term,levels=c("Factor Score",
                                   "Pro Free Trade",
                                   "Increase Immigration Limits",
                                   "Anti-Isolationism",
                                   "Decrease Defense Spending"))) %>%
  arrange(factor(model, levels=c("Donor","Affluent"))) %>% 
  arrange(factor(term, levels=c("Factor Score",
                                "Pro Free Trade",
                                "Increase Immigration Limits",
                                "Anti-Isolationism",
                                "Decrease Defense Spending"))) %>%
  mutate(LCI=estimate-std.error*1.96) %>%
  mutate(UCI=estimate+std.error*1.96)

nrows <- length(varlist_globalist)
offset <- .2

pdf(file=paste(outdir_figures,"SI_FigureA2_Figure2_weighted.pdf", sep=""))
plot(x=c(-.5,.4),y=c(1,2*length(varlist_globalist)+4),type="n",axes=FALSE,
     xlab="Difference from Copartisan \n  General Population Mean (and 95% CI)",
     ylab="",
     main = "Average Policy Differences \n Among Donors, Affluent, and General Public")
abline(v=seq(-.3,.3,by=.05),lty=2,col="light grey")
abline(v=0)
axis(1,at=seq(-.3,.3,by=.1),
     labels=c(-.3,-.2,-.1,0,.1,.2,.3))

# democrats
for(i in 1: length(varlist_globalist)){
  donor_row <- reg2b_wt %>%
    filter(term == varlist_globalist_names[varlist_globalist[nrows-i+1]], model == "Donor")
  affluent_row <- reg2b_wt %>%
    filter(term == varlist_globalist_names[varlist_globalist[nrows-i+1]], model == "Affluent")
  
  # point estimate
  points(x=donor_row$estimate, y=i+1+offset,pch=16)
  points(x=affluent_row$estimate, y=i+1-offset, col = "GREY", pch = 18)
  
  segments(x0 = donor_row$LCI, y0 = i+1+offset, x1 = donor_row$UCI, y1 = i+1+offset)
  segments(x0 = affluent_row$LCI, y0 = i+1-offset, x1 = affluent_row$UCI, y1 = i+1-offset, col = "grey")
}

text(labels=rev(varlist_globalist_names),x=rep(-.4,times=length(varlist_globalist)),
     y=1+seq(1,length(varlist_globalist)),cex=textsize,pos=4)
text(labels = "Democrats", x = -.4, y = 4,srt=90)

legend(.1,8.5, legend=c("Donors", "Affluent"), col=c("black","light grey"), pch=c(16,18),cex=.75)

# republicans
for(i in 1: length(varlist_globalist)){
  donor_row <- reg2a_wt %>%
    filter(term == varlist_globalist_names[varlist_globalist[nrows-i+1]], model == "Donor")
  affluent_row <- reg2a_wt %>%
    filter(term == varlist_globalist_names[varlist_globalist[nrows-i+1]], model == "Affluent")
  
  # point estimate
  points(x=donor_row$estimate, y=i+3+length(varlist_globalist)+offset,pch=16)
  points(x=affluent_row$estimate, y=i+3+length(varlist_globalist)-offset, col = "GREY", pch = 18)
  
  segments(x0 = donor_row$LCI, y0 = i+3+length(varlist_globalist)+offset, x1 = donor_row$UCI, y1 = i+3+length(varlist_globalist)+offset)
  segments(x0 = affluent_row$LCI, y0 = i+3+length(varlist_globalist)-offset, x1 = affluent_row$UCI, y1 = i+3+length(varlist_globalist)-offset, col = "grey")
}

text(labels=rev(varlist_globalist_names),x= rep(-.4,times=length(varlist_globalist)),
     y=3+length(varlist_globalist)+seq(1,length(varlist_globalist)),cex=textsize,pos=4)
text(labels = "Republicans", x = -.4, y = 11,srt=90)
text(labels = "Less Internationalist", x = -.15, y = 3+length(varlist_globalist)+nrows+1,cex=.75)
text(labels = "More Internationalist", x = .1, y = 3+length(varlist_globalist)+nrows+1,cex=.75)
text(labels = "Less Internationalist", x = -.15, y = 1,cex=.75)
text(labels = "More Internationalist", x = .1, y = 1,cex=.75)
dev.off()

############################################################################################################################################################################
# Table A2. International Issues Difference of Means Comparisons by Sample with Weights (Figure A2).
############################################################################################################################################################################

reg2a_wt$Party <- "Republicans"
reg2b_wt$Party <- "Democrats"
reg2_wt <- rbind(reg2a_wt, reg2b_wt)
reg2_wt <- reg2_wt %>%
  rename(Issue=term,
         Group=model,
         Estimate=estimate,
         `Standard Error`=std.error) %>%
  select(Party, Issue, Group, Estimate, `Standard Error`)

reg2_wt <- as.data.frame(reg2_wt) %>%
  arrange(Group, Issue, Party)

reg2_wt$`Standard Error` = paste0("(",sprintf(reg2_wt$`Standard Error`, fmt="%.3f"),")")
reg2_wt$Estimate = sprintf(reg2_wt$Estimate, fmt="%.3f")

reg2_wt_ <- reg2_wt %>%
  pivot_longer(cols=c("Estimate", "Standard Error")) %>%
  pivot_wider(names_from=c("Group","Party"))

reg2_wt_$Issue = as.character(reg2_wt_$Issue)
reg2_wt_$Issue[reg2_wt_$name=="Standard Error"] = ""

reg2_wt_ <- reg2_wt_ %>%
  select("Issue", "Donor_Democrats", "Donor_Republicans", "Affluent_Democrats", "Affluent_Republicans")

kbl(reg2_wt_, "html", 
    col.names = c("", "Democrats", 
                  "Republicans", "Democrats", "Republicans")) %>%
  kable_classic(full_width=F, html_font="Cambria") %>%
  add_header_above(c(" " = 1, "Donors" = 2, "Affluent" = 2)) %>%
  cat(., file=paste(outdir_tables, "SI_TableA2_figure_A2_weighted.html", sep=""))




############################################################################################################################################################################
#  Figure A3. Figure 1 Replication with Pure Independents and Respondent Weights
############################################################################################################################################################################

# Republicans Regression
dat1a_wt <- dat_wt %>%
  filter(republican==1 | d_pid7 == "Independent") %>%
  mutate(sample=as.factor(sample)) %>%
  mutate(sample=relevel(sample, ref="Gen Pop"))

rawdat1a_wt <- dat1a_wt %>%
  select(sample,varlist_general,invpropensitywgt) %>%  
  pivot_longer(names_to = "Variable", cols = varlist_general) %>%
  select(sample,Variable,invpropensitywgt,value) %>%
  drop_na()

reg1a_wt <- rawdat1a_wt %>%
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ sample, data = ., weights=invpropensitywgt))) %>% # run model for each variable
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(model=recode(model,
                      sampleAffluent = "Affluent",
                      sampleDonor = "Donor")) %>%
  arrange(factor(model, levels=c("Donor","Affluent"))) %>% 
  arrange(factor(term, levels=varlist_general))%>%
  mutate(model=factor(model, levels=c("Donor", "Affluent"))) %>%
  mutate(term=recode(term,
                     fa_all="Factor Score",
                     f_01_minwagejoint="Increase Minimum Wage",
                     i_01_taxes1="Incr. Top Marginal Tax Rate",
                     f_01_tanfjoint="Increase TANF Spending",
                     f_01_sumenvironment="Pro Environmentalism",
                     i_01_health3="Incr. Govt Role in Health Care",
                     f_01_abortionjoint="Fewer Abortion Restrictions",
                     i_01_rguncontrol="More Gun Control")) %>%
  mutate(term=factor(term, levels=c("Factor Score", 
                                    "Increase Minimum Wage",
                                    "Incr. Top Marginal Tax Rate",
                                    "Increase TANF Spending",
                                    "Pro Environmentalism",
                                    "Incr. Govt Role in Health Care",
                                    "Fewer Abortion Restrictions",
                                    "More Gun Control"))) %>%
  mutate(LCI=estimate-std.error*1.96) %>%
  mutate(UCI=estimate+std.error*1.96)

# Democrats Regression
dat1b_wt <- dat_wt %>%
  filter(democrat==1 | d_pid7 == "Independent") %>%
  mutate(sample=as.factor(sample)) %>%
  mutate(sample=relevel(sample, ref="Gen Pop"))

rawdat1b_wt <- dat1b_wt %>%
  select(sample,varlist_general,invpropensitywgt) %>%  
  pivot_longer(names_to = "Variable", cols = varlist_general) %>%
  select(sample,Variable,invpropensitywgt,value) %>%
  drop_na()

reg1b_wt <- rawdat1b_wt %>%
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ sample, data = ., weights=invpropensitywgt))) %>% # run model for each variable
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(model=recode(model,
                      sampleAffluent = "Affluent",
                      sampleDonor = "Donor")) %>%
  arrange(factor(model, levels=c("Donor","Affluent"))) %>% 
  arrange(factor(term, levels=varlist_general))%>%
  mutate(model=factor(model, levels=c("Donor", "Affluent"))) %>%
  mutate(term=recode(term,
                     fa_all="Factor Score",
                     f_01_minwagejoint="Increase Minimum Wage",
                     i_01_taxes1="Incr. Top Marginal Tax Rate",
                     f_01_tanfjoint="Increase TANF Spending",
                     f_01_sumenvironment="Pro Environmentalism",
                     i_01_health3="Incr. Govt Role in Health Care",
                     f_01_abortionjoint="Fewer Abortion Restrictions",
                     i_01_rguncontrol="More Gun Control")) %>%
  mutate(term=factor(term, levels=c("Factor Score", 
                                    "Increase Minimum Wage",
                                    "Incr. Top Marginal Tax Rate",
                                    "Increase TANF Spending",
                                    "Pro Environmentalism",
                                    "Incr. Govt Role in Health Care",
                                    "Fewer Abortion Restrictions",
                                    "More Gun Control"))) %>%
  mutate(LCI=estimate-std.error*1.96) %>%
  mutate(UCI=estimate+std.error*1.96)


nrows <- length(varlist_general)
offset <- .2

pdf(file=paste(outdir_figures,"SI_FigureA3_Figure1_WithIndepWeighted.pdf", sep=""))

plot(x=c(-.4,.25),y=c(1,2*length(varlist_general)+5),type="n",axes=FALSE,
     xlab="Difference from General Population Mean \n of Copartisans & Independents (and 95% CI)",
     ylab="",
     main = "Average Policy Differences \n Among Donors, Affluent, and General Public")
abline(v=seq(-.3,.15,by=.05),lty=2,col="light grey")
abline(v=0)
axis(1,at=seq(-.3,.2,by=.05),
     labels=c(-.3,-.25,-.2,-.15,-.1,-.05,0,.05,.1,.15,.2))

# democrats
for(i in 1: length(varlist_general)){
  donor_row <- reg1b_wt %>%
    filter(term == varlist_names[varlist_general[nrows-i+1]], model == "Donor")
  affluent_row <- reg1b_wt %>%
    filter(term == varlist_names[varlist_general[nrows-i+1]], model == "Affluent")
  
  # point estimate
  points(x=donor_row$estimate, y=i+1+offset,pch=16)
  points(x=affluent_row$estimate, y=i+1-offset, col = "GREY", pch = 18)
  
  segments(x0 = donor_row$LCI, y0 = i+1+offset, x1 = donor_row$UCI, y1 = i+1+offset)
  segments(x0 = affluent_row$LCI, y0 = i+1-offset, x1 = affluent_row$UCI, y1 = i+1-offset, col = "grey")
}

text(labels=rev(varlist_names),x=rep(-.4,times=length(varlist_general)),
     y=1+seq(1,length(varlist_general)),cex=textsize,pos=4)
text(labels = "Democrats", x = -.4, y = 5.5,srt=90)

legend(.1,13, legend=c("Donors", "Affluent"), col=c("black","light grey"), pch=c(16,18),cex=.75)

# republicans
for(i in 1: length(varlist_general)){
  donor_row <- reg1a_wt %>%
    filter(term == varlist_names[varlist_general[nrows-i+1]], model == "Donor")
  affluent_row <- reg1a_wt %>%
    filter(term == varlist_names[varlist_general[nrows-i+1]], model == "Affluent")
  
  # point estimate
  points(x=donor_row$estimate, y=i+3+length(varlist_general)+offset,pch=16)
  points(x=affluent_row$estimate, y=i+3+length(varlist_general)-offset, col = "GREY", pch = 18)
  
  segments(x0 = donor_row$LCI, y0 = i+3+length(varlist_general)+offset, x1 = donor_row$UCI, y1 = i+3+length(varlist_general)+offset)
  segments(x0 = affluent_row$LCI, y0 = i+3+length(varlist_general)-offset, x1 = affluent_row$UCI, y1 = i+3+length(varlist_general)-offset, col = "grey")
}

text(labels=rev(varlist_names),x= rep(-.4,times=length(varlist_general)),
     y=3+length(varlist_general)+seq(1,length(varlist_general)),cex=textsize,pos=4)
text(labels = "Republicans", x = -.4, y = 16,srt=90)
text(labels = "More Conservative", x = -.15, y = 4+length(varlist_general)+nrows+1,cex=.75)
text(labels = "More Liberal", x = .1, y = 4+length(varlist_general)+nrows+1,cex=.75)
text(labels = "More Conservative", x = -.15, y = 1,cex=.75)
text(labels = "More Liberal", x = .1, y = 1,cex=.75)
dev.off()


############################################################################################################################################################################
# Figure A4. Figure 2 Replication with Pure Independents and Respondent Weights
############################################################################################################################################################################

# republicans
dat2a_wt <- dat_wt %>%
  filter(republican==1 | d_pid7 == "Independent") %>%
  mutate(sample=as.factor(sample)) %>%
  mutate(sample=relevel(sample, ref="Gen Pop"))

rawdat2a_wt <- dat2a_wt %>%
  select(sample,varlist_globalist,invpropensitywgt) %>%  
  pivot_longer(names_to = "Variable", cols = varlist_globalist) %>%
  select(sample,Variable,invpropensitywgt,value) %>%
  drop_na()

reg2a_wt <- rawdat2a_wt %>%
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ sample, data = ., weights=invpropensitywgt))) %>% # run model for each variable
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(model=recode(model,
                      sampleAffluent = "Affluent",
                      sampleDonor = "Donor")) %>%
  mutate(model=factor(model, levels=c("Donor", "Affluent"))) %>%
  mutate(term=recode(term,
                     fa_global="Factor Score",
                     i_01_rtrade="Pro Free Trade",
                     i_01_immigration5="Increase Immigration Limits",
                     i_01_risolation="Anti-Isolationism",
                     f_01_rdefensejoint="Decrease Defense Spending")) %>%
  mutate(term=factor(term,levels=c("Factor Score",
                                   "Pro Free Trade",
                                   "Increase Immigration Limits",
                                   "Anti-Isolationism",
                                   "Decrease Defense Spending"))) %>%
  arrange(factor(model, levels=c("Donor","Affluent"))) %>% 
  arrange(factor(term, levels=c("Factor Score",
                                "Pro Free Trade",
                                "Increase Immigration Limits",
                                "Anti-Isolationism",
                                "Decrease Defense Spending"))) %>%
  mutate(LCI=estimate-std.error*1.96) %>%
  mutate(UCI=estimate+std.error*1.96)

# democrats

dat2b_wt <- dat_wt %>%
  filter(democrat==1 | d_pid7 == "Independent") %>%
  mutate(sample=as.factor(sample)) %>%
  mutate(sample=relevel(sample, ref="Gen Pop"))

rawdat2b_wt <- dat2b_wt %>%
  select(sample,varlist_globalist,invpropensitywgt) %>%  
  pivot_longer(names_to = "Variable", cols = varlist_globalist) %>%
  select(sample,Variable,invpropensitywgt,value) %>%
  drop_na()

reg2b_wt <- rawdat2b_wt %>%
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ sample, data = ., weights=invpropensitywgt))) %>% # run model for each variable
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(model=recode(model,
                      sampleAffluent = "Affluent",
                      sampleDonor = "Donor")) %>%
  arrange(factor(model, levels=c("Donor","Affluent"))) %>% 
  arrange(factor(term, levels=varlist_general))%>%
  mutate(model=factor(model, levels=c("Donor", "Affluent"))) %>%
  mutate(term=recode(term,
                     fa_global="Factor Score",
                     i_01_rtrade="Pro Free Trade",
                     i_01_risolation="Anti-Isolationism",
                     i_01_immigration5="Increase Immigration Limits",
                     f_01_rdefensejoint="Decrease Defense Spending")) %>%
  mutate(term=factor(term,levels=c("Factor Score",
                                   "Pro Free Trade",
                                   "Increase Immigration Limits",
                                   "Anti-Isolationism",
                                   "Decrease Defense Spending"))) %>%
  arrange(factor(model, levels=c("Donor","Affluent"))) %>% 
  arrange(factor(term, levels=c("Factor Score",
                                "Pro Free Trade",
                                "Increase Immigration Limits",
                                "Anti-Isolationism",
                                "Decrease Defense Spending"))) %>%
  mutate(LCI=estimate-std.error*1.96) %>%
  mutate(UCI=estimate+std.error*1.96)

nrows <- length(varlist_globalist)
offset <- .2

pdf(file=paste(outdir_figures,"SI_FigureA4_Figure2_WithIndepWeighted.pdf", sep=""))
plot(x=c(-.5,.4),y=c(1,2*length(varlist_globalist)+4),type="n",axes=FALSE,
     xlab="Difference from General Population Mean \n of Copartisans and Independents (and 95% CI)",
     ylab="",
     main = "Average Policy Differences \n Among Donors, Affluent, and General Public")
abline(v=seq(-.3,.3,by=.05),lty=2,col="light grey")
abline(v=0)
axis(1,at=seq(-.3,.3,by=.1),
     labels=c(-.3,-.2,-.1,0,.1,.2,.3))

# democrats
for(i in 1: length(varlist_globalist)){
  donor_row <- reg2b_wt %>%
    filter(term == varlist_globalist_names[varlist_globalist[nrows-i+1]], model == "Donor")
  affluent_row <- reg2b_wt %>%
    filter(term == varlist_globalist_names[varlist_globalist[nrows-i+1]], model == "Affluent")
  
  # point estimate
  points(x=donor_row$estimate, y=i+1+offset,pch=16)
  points(x=affluent_row$estimate, y=i+1-offset, col = "GREY", pch = 18)
  
  segments(x0 = donor_row$LCI, y0 = i+1+offset, x1 = donor_row$UCI, y1 = i+1+offset)
  segments(x0 = affluent_row$LCI, y0 = i+1-offset, x1 = affluent_row$UCI, y1 = i+1-offset, col = "grey")
}

text(labels=rev(varlist_globalist_names),x=rep(-.4,times=length(varlist_globalist)),
     y=1+seq(1,length(varlist_globalist)),cex=textsize,pos=4)
text(labels = "Democrats", x = -.4, y = 4,srt=90)

legend(.1,8.5, legend=c("Donors", "Affluent"), col=c("black","light grey"), pch=c(16,18),cex=.75)

# republicans
for(i in 1: length(varlist_globalist)){
  donor_row <- reg2a_wt %>%
    filter(term == varlist_globalist_names[varlist_globalist[nrows-i+1]], model == "Donor")
  affluent_row <- reg2a_wt %>%
    filter(term == varlist_globalist_names[varlist_globalist[nrows-i+1]], model == "Affluent")
  
  # point estimate
  points(x=donor_row$estimate, y=i+3+length(varlist_globalist)+offset,pch=16)
  points(x=affluent_row$estimate, y=i+3+length(varlist_globalist)-offset, col = "GREY", pch = 18)
  
  segments(x0 = donor_row$LCI, y0 = i+3+length(varlist_globalist)+offset, x1 = donor_row$UCI, y1 = i+3+length(varlist_globalist)+offset)
  segments(x0 = affluent_row$LCI, y0 = i+3+length(varlist_globalist)-offset, x1 = affluent_row$UCI, y1 = i+3+length(varlist_globalist)-offset, col = "grey")
}

text(labels=rev(varlist_globalist_names),x= rep(-.4,times=length(varlist_globalist)),
     y=3+length(varlist_globalist)+seq(1,length(varlist_globalist)),cex=textsize,pos=4)
text(labels = "Republicans", x = -.4, y = 11,srt=90)
text(labels = "Less Internationalist", x = -.15, y = 3+length(varlist_globalist)+nrows+1,cex=.75)
text(labels = "More Internationalist", x = .1, y = 3+length(varlist_globalist)+nrows+1,cex=.75)
text(labels = "Less Internationalist", x = -.15, y = 1,cex=.75)
text(labels = "More Internationalist", x = .1, y = 1,cex=.75)
dev.off()


############################################################################################################################################################################
#       Figure A5. Figure 1 Robustness: Comparing Affluent and General Population Domestic Policy Views (Incl. Pure Independents)
############################################################################################################################################################################

# Republicans Regression
dat1a_wt <- dat_wt %>%
  filter(republican==1 | d_pid7 == "Independent") %>%
  mutate(sample=as.factor(sample)) %>%
  filter(sample != "Donor") %>%
  mutate(sample=relevel(sample, ref="Gen Pop"))

rawdat1a_wt <- dat1a_wt %>%
  select(sample,varlist_general,invpropensitywgt) %>%  
  pivot_longer(names_to = "Variable", cols = varlist_general) %>%
  select(sample,Variable,invpropensitywgt,value) %>%
  drop_na()

reg1a_wt <- rawdat1a_wt %>%
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ sample, data = ., weights=invpropensitywgt))) %>% # run model for each variable
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(model=recode(model,
                      sampleAffluent = "Affluent",
                      sampleDonor = "Donor")) %>%
  arrange(factor(model, levels=c("Donor","Affluent"))) %>% 
  arrange(factor(term, levels=varlist_general))%>%
  mutate(model=factor(model, levels=c("Donor", "Affluent"))) %>%
  mutate(term=recode(term,
                     fa_all="Factor Score",
                     f_01_minwagejoint="Increase Minimum Wage",
                     i_01_taxes1="Incr. Top Marginal Tax Rate",
                     f_01_tanfjoint="Increase TANF Spending",
                     f_01_sumenvironment="Pro Environmentalism",
                     i_01_health3="Incr. Govt Role in Health Care",
                     f_01_abortionjoint="Fewer Abortion Restrictions",
                     i_01_rguncontrol="More Gun Control")) %>%
  mutate(term=factor(term, levels=c("Factor Score", 
                                    "Increase Minimum Wage",
                                    "Incr. Top Marginal Tax Rate",
                                    "Increase TANF Spending",
                                    "Pro Environmentalism",
                                    "Incr. Govt Role in Health Care",
                                    "Fewer Abortion Restrictions",
                                    "More Gun Control"))) %>%
  mutate(LCI=estimate-std.error*1.96) %>%
  mutate(UCI=estimate+std.error*1.96)

# Democrats Regression
dat1b_wt <- dat_wt %>%
  filter(democrat==1 | d_pid7 == "Independent") %>%
  mutate(sample=as.factor(sample)) %>%
  mutate(sample=relevel(sample, ref="Gen Pop"))

rawdat1b_wt <- dat1b_wt %>%
  select(sample,varlist_general,invpropensitywgt) %>%  
  pivot_longer(names_to = "Variable", cols = varlist_general) %>%
  select(sample,Variable,invpropensitywgt,value) %>%
  drop_na()

reg1b_wt <- rawdat1b_wt %>%
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ sample, data = ., weights=invpropensitywgt))) %>% # run model for each variable
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(model=recode(model,
                      sampleAffluent = "Affluent",
                      sampleDonor = "Donor")) %>%
  arrange(factor(model, levels=c("Donor","Affluent"))) %>% 
  arrange(factor(term, levels=varlist_general))%>%
  mutate(model=factor(model, levels=c("Donor", "Affluent"))) %>%
  mutate(term=recode(term,
                     fa_all="Factor Score",
                     f_01_minwagejoint="Increase Minimum Wage",
                     i_01_taxes1="Incr. Top Marginal Tax Rate",
                     f_01_tanfjoint="Increase TANF Spending",
                     f_01_sumenvironment="Pro Environmentalism",
                     i_01_health3="Incr. Govt Role in Health Care",
                     f_01_abortionjoint="Fewer Abortion Restrictions",
                     i_01_rguncontrol="More Gun Control")) %>%
  mutate(term=factor(term, levels=c("Factor Score", 
                                    "Increase Minimum Wage",
                                    "Incr. Top Marginal Tax Rate",
                                    "Increase TANF Spending",
                                    "Pro Environmentalism",
                                    "Incr. Govt Role in Health Care",
                                    "Fewer Abortion Restrictions",
                                    "More Gun Control"))) %>%
  mutate(LCI=estimate-std.error*1.96) %>%
  mutate(UCI=estimate+std.error*1.96)

##############
# Make figure
##############

nrows <- length(varlist_general)
offset <- .2

pdf(file=paste(outdir_figures,"SI_FigureA5_Figure2_AffluentVsGenPopIndepWeighted.pdf", sep=""))

plot(x=c(-.4,.25),y=c(1,2*length(varlist_general)+5),type="n",axes=FALSE,
     xlab="Difference from General Population Mean \n of Copartisans & Independents (and 95% CI)",
     ylab="",
     main = "Average Policy Differences \n Among Affluent and General Public")
abline(v=seq(-.3,.15,by=.05),lty=2,col="light grey")
abline(v=0)
axis(1,at=seq(-.3,.2,by=.05),
     labels=c(-.3,-.25,-.2,-.15,-.1,-.05,0,.05,.1,.15,.2))

# democrats
for(i in 1: length(varlist_general)){
  affluent_row <- reg1b_wt %>%
    filter(term == varlist_names[varlist_general[nrows-i+1]], model == "Affluent")
  
  # point estimate
  points(x=affluent_row$estimate, y=i+1-offset, col = "GREY", pch = 18)
  segments(x0 = affluent_row$LCI, y0 = i+1-offset, x1 = affluent_row$UCI, y1 = i+1-offset, col = "grey")
}

text(labels=rev(varlist_names),x=rep(-.4,times=length(varlist_general)),
     y=1+seq(1,length(varlist_general)),cex=textsize,pos=4)
text(labels = "Democrats", x = -.4, y = 5.5,srt=90)

# republicans
for(i in 1: length(varlist_general)){
  affluent_row <- reg1a_wt %>%
    filter(term == varlist_names[varlist_general[nrows-i+1]], model == "Affluent")
  
  # point estimate
  points(x=affluent_row$estimate, y=i+3+length(varlist_general)-offset, col = "GREY", pch = 18)
  segments(x0 = affluent_row$LCI, y0 = i+3+length(varlist_general)-offset, x1 = affluent_row$UCI, y1 = i+3+length(varlist_general)-offset, col = "grey")
}

text(labels=rev(varlist_names),x= rep(-.4,times=length(varlist_general)),
     y=3+length(varlist_general)+seq(1,length(varlist_general)),cex=textsize,pos=4)
text(labels = "Republicans", x = -.4, y = 16,srt=90)
text(labels = "More Conservative", x = -.15, y = 4+length(varlist_general)+nrows+1,cex=.75)
text(labels = "More Liberal", x = .1, y = 4+length(varlist_general)+nrows+1,cex=.75)
text(labels = "More Conservative", x = -.15, y = 1,cex=.75)
text(labels = "More Liberal", x = .1, y = 1,cex=.75)
dev.off()



############################################################################################################################################################################
# Figure A6. Figure 2 Robustness: Comparing Affluent and General Population International Policy Views (Incl. Pure Independents)
############################################################################################################################################################################

# republicans
dat2a_wt <- dat_wt %>%
  filter(republican==1 | d_pid7 == "Independent") %>%
  filter(sample != "Donor") %>%
  mutate(sample=as.factor(sample)) %>%
  mutate(sample=relevel(sample, ref="Gen Pop"))

rawdat2a_wt <- dat2a_wt %>%
  select(sample,varlist_globalist,invpropensitywgt) %>%  
  pivot_longer(names_to = "Variable", cols = varlist_globalist) %>%
  select(sample,Variable,invpropensitywgt,value) %>%
  drop_na()

reg2a_wt <- rawdat2a_wt %>%
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ sample, data = ., weights=invpropensitywgt))) %>% # run model for each variable
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(model=recode(model,
                      sampleAffluent = "Affluent",
                      sampleDonor = "Donor")) %>%
  mutate(model=factor(model, levels=c("Donor", "Affluent"))) %>%
  mutate(term=recode(term,
                     fa_global="Factor Score",
                     i_01_rtrade="Pro Free Trade",
                     i_01_immigration5="Increase Immigration Limits",
                     i_01_risolation="Anti-Isolationism",
                     f_01_rdefensejoint="Decrease Defense Spending")) %>%
  mutate(term=factor(term,levels=c("Factor Score",
                                   "Pro Free Trade",
                                   "Increase Immigration Limits",
                                   "Anti-Isolationism",
                                   "Decrease Defense Spending"))) %>%
  arrange(factor(model, levels=c("Donor","Affluent"))) %>% 
  arrange(factor(term, levels=c("Factor Score",
                                "Pro Free Trade",
                                "Increase Immigration Limits",
                                "Anti-Isolationism",
                                "Decrease Defense Spending"))) %>%
  mutate(LCI=estimate-std.error*1.96) %>%
  mutate(UCI=estimate+std.error*1.96)

# democrats

dat2b_wt <- dat_wt %>%
  filter(democrat==1 | d_pid7 == "Independent") %>%
  filter(sample != "Donor") %>%
  mutate(sample=as.factor(sample)) %>%
  mutate(sample=relevel(sample, ref="Gen Pop"))

rawdat2b_wt <- dat2b_wt %>%
  select(sample,varlist_globalist,invpropensitywgt) %>%  
  pivot_longer(names_to = "Variable", cols = varlist_globalist) %>%
  select(sample,Variable,invpropensitywgt,value) %>%
  drop_na()

reg2b_wt <- rawdat2b_wt %>%
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ sample, data = ., weights=invpropensitywgt))) %>% # run model for each variable
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(model=recode(model,
                      sampleAffluent = "Affluent",
                      sampleDonor = "Donor")) %>%
  arrange(factor(model, levels=c("Donor","Affluent"))) %>% 
  arrange(factor(term, levels=varlist_general))%>%
  mutate(model=factor(model, levels=c("Donor", "Affluent"))) %>%
  mutate(term=recode(term,
                     fa_global="Factor Score",
                     i_01_rtrade="Pro Free Trade",
                     i_01_risolation="Anti-Isolationism",
                     i_01_immigration5="Increase Immigration Limits",
                     f_01_rdefensejoint="Decrease Defense Spending")) %>%
  mutate(term=factor(term,levels=c("Factor Score",
                                   "Pro Free Trade",
                                   "Increase Immigration Limits",
                                   "Anti-Isolationism",
                                   "Decrease Defense Spending"))) %>%
  arrange(factor(model, levels=c("Donor","Affluent"))) %>% 
  arrange(factor(term, levels=c("Factor Score",
                                "Pro Free Trade",
                                "Increase Immigration Limits",
                                "Anti-Isolationism",
                                "Decrease Defense Spending"))) %>%
  mutate(LCI=estimate-std.error*1.96) %>%
  mutate(UCI=estimate+std.error*1.96)

nrows <- length(varlist_globalist)
offset <- .2

pdf(file=paste(outdir_figures,"SI_FigureA6_Figure2_AffluentVsGenPopIndepWeighted.pdf", sep=""))
plot(x=c(-.5,.4),y=c(1,2*length(varlist_globalist)+4),type="n",axes=FALSE,
     xlab="Difference from General Population Mean \n of Copartisans and Independents (and 95% CI)",
     ylab="",
     main = "Average Policy Differences \n Among Affluent and General Public")
abline(v=seq(-.3,.3,by=.05),lty=2,col="light grey")
abline(v=0)
axis(1,at=seq(-.3,.3,by=.1),
     labels=c(-.3,-.2,-.1,0,.1,.2,.3))

# democrats
for(i in 1: length(varlist_globalist)){
  affluent_row <- reg2b_wt %>%
    filter(term == varlist_globalist_names[varlist_globalist[nrows-i+1]], model == "Affluent")
  # point estimate
  points(x=affluent_row$estimate, y=i+1-offset, col = "GREY", pch = 18)
  segments(x0 = affluent_row$LCI, y0 = i+1-offset, x1 = affluent_row$UCI, y1 = i+1-offset, col = "grey")
}

text(labels=rev(varlist_globalist_names),x=rep(-.4,times=length(varlist_globalist)),
     y=1+seq(1,length(varlist_globalist)),cex=textsize,pos=4)
text(labels = "Democrats", x = -.4, y = 4,srt=90)

# republicans
for(i in 1: length(varlist_globalist)){
  affluent_row <- reg2a_wt %>%
    filter(term == varlist_globalist_names[varlist_globalist[nrows-i+1]], model == "Affluent")
  
  # point estimate
  points(x=affluent_row$estimate, y=i+3+length(varlist_globalist)-offset, col = "GREY", pch = 18)
  segments(x0 = affluent_row$LCI, y0 = i+3+length(varlist_globalist)-offset, x1 = affluent_row$UCI, y1 = i+3+length(varlist_globalist)-offset, col = "grey")
}

text(labels=rev(varlist_globalist_names),x= rep(-.4,times=length(varlist_globalist)),
     y=3+length(varlist_globalist)+seq(1,length(varlist_globalist)),cex=textsize,pos=4)
text(labels = "Republicans", x = -.4, y = 11,srt=90)
text(labels = "Less Internationalist", x = -.15, y = 3+length(varlist_globalist)+nrows+1,cex=.75)
text(labels = "More Internationalist", x = .1, y = 3+length(varlist_globalist)+nrows+1,cex=.75)
text(labels = "Less Internationalist", x = -.15, y = 1,cex=.75)
text(labels = "More Internationalist", x = .1, y = 1,cex=.75)
dev.off()


############################################################################################
############################################################################################
# APPENDIX B
############################################################################################
############################################################################################

############################################################################################################################################################################
# Table B1. Figure 1 Means and Differences: Domestic Issues Comparisons by Sample.
############################################################################################################################################################################

reg1a$Party <- "Republicans"
reg1b$Party <- "Democrats"
reg1 <- rbind(reg1a, reg1b)
reg1 <- reg1 %>%
  rename(Issue=term,
         Group=model,
         Estimate=estimate,
         `Standard Error`=std.error) %>%
  select(Party, Issue, Group, Estimate, `Standard Error`)

reg1 <- as.data.frame(reg1) %>%
  arrange(Group, Issue, Party)

reg1$`Standard Error` = paste0("(",sprintf(reg1$`Standard Error`, fmt="%.3f"),")")
reg1$Estimate = sprintf(reg1$Estimate, fmt="%.3f")

reg1_ <- reg1 %>%
  pivot_longer(cols=c("Estimate", "Standard Error")) %>%
  pivot_wider(names_from=c("Group","Party"))

reg1_$Issue = as.character(reg1_$Issue)
reg1_$Issue[reg1_$name=="Standard Error"] = ""

reg1_ <- reg1_ %>%
  select("Issue", "Donor_Democrats", "Donor_Republicans", "Affluent_Democrats", "Affluent_Republicans")

kbl(reg1_, "html", 
    col.names = c("", "Democrats", 
                  "Republicans", "Democrats", "Republicans")) %>%
  kable_classic(full_width=F, html_font="Times New Roman") %>%
  add_header_above(c(" " = 1, "Donors" = 2, "Affluent" = 2)) %>%
  cat(., file=paste(outdir_tables, "SI_TableB1_Figure1.html", sep=""))

# Table B1 P-Values for Difference of Means on Domestic Issues Between Donors and Affluent.

reg1a_pv <- rawdat1a %>%
  filter(sample!="Gen Pop") %>%
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ sample, data = .))) %>% # run model for each variable
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  arrange(factor(term, levels=varlist_general))%>%
  mutate(term=recode(term,
                     fa_all="Factor Score",
                     f_01_minwagejoint="Increase Minimum Wage",
                     i_01_taxes1="Incr. Top Marginal Tax Rate",
                     f_01_tanfjoint="Increase TANF Spending",
                     f_01_sumenvironment="Pro Environmentalism",
                     i_01_health3="Incr. Govt Role in Health Care",
                     f_01_abortionjoint="Fewer Abortion Restrictions",
                     i_01_rguncontrol="More Gun Control"))
reg1b_pv <- rawdat1b %>%
  filter(sample!="Gen Pop") %>%
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ sample, data = .))) %>% # run model for each variable
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  arrange(factor(term, levels=varlist_general))%>%
  mutate(term=recode(term,
                     fa_all="Factor Score",
                     f_01_minwagejoint="Increase Minimum Wage",
                     i_01_taxes1="Incr. Top Marginal Tax Rate",
                     f_01_tanfjoint="Increase TANF Spending",
                     f_01_sumenvironment="Pro Environmentalism",
                     i_01_health3="Incr. Govt Role in Health Care",
                     f_01_abortionjoint="Fewer Abortion Restrictions",
                     i_01_rguncontrol="More Gun Control"))
reg1a_pv$Party <- "Republicans"
reg1b_pv$Party <- "Democrats"
reg1_pv <- rbind(reg1a_pv, reg1b_pv)
reg1_pv <- reg1_pv %>%
  rename(
    Group=model,
    Estimate=estimate,
    `P-Value`=p.value) %>%
  select(Party, `P-Value`) %>%
  arrange(term, Party)

reg1_pv <- as.data.frame(reg1_pv)

reg1_pv <- reg1_pv %>%
  pivot_wider(names_from=c("Party"), values_from=c("P-Value"))

############################################################################################################################################################################
# Table B2. Figure 2 Means and Differences: International Issues Comparisons by Sample. 
############################################################################################################################################################################

reg2a$Party <- "Republicans"
reg2b$Party <- "Democrats"
reg2 <- rbind(reg2a, reg2b)
reg2 <- reg2 %>%
  rename(Issue=term,
         Group=model,
         Estimate=estimate,
         `Standard Error`=std.error) %>%
  select(Party, Issue, Group, Estimate, `Standard Error`) %>% 
  arrange(factor(Issue, levels=c("Factor Score","Pro Free Trade","Increase Immigration Limits","Anti-Isolationism","Decrease Defense Spending")))

reg2 <- as.data.frame(reg2) %>%
  arrange(Group, Issue, Party) %>% 
  arrange(factor(Issue, levels=c("Factor Score","Pro Free Trade","Increase Immigration Limits","Anti-Isolationism","Decrease Defense Spending")))


reg2$`Standard Error` = paste0("(",sprintf(reg2$`Standard Error`, fmt="%.3f"),")")
reg2$Estimate = sprintf(reg2$Estimate, fmt="%.3f")

reg2_ <- reg2 %>%
  pivot_longer(cols=c("Estimate", "Standard Error")) %>%
  pivot_wider(names_from=c("Group","Party"))

reg2_$Issue = as.character(reg2_$Issue)
reg2_$Issue[reg2_$name=="Standard Error"] = ""

reg2_ <- reg2_ %>%
  select("Issue", "Donor_Democrats", "Donor_Republicans", "Affluent_Democrats", "Affluent_Republicans")

kbl(reg2_, "html", 
    col.names = c("", "Democrats", 
                  "Republicans", "Democrats", "Republicans")) %>%
  kable_classic(full_width=F, html_font="Times New Roman") %>%
  add_header_above(c(" " = 1, "Donors" = 2, "Affluent" = 2)) %>%
  cat(., file=paste(outdir_tables, "SI_TableB2_Figure2.html", sep=""))


# Table B2 P-Values for Difference of Means on International Issues Between Donors and Affluent.

reg2a_pv <- rawdat2a %>%
  filter(sample!="Gen Pop") %>%
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ sample, data = .))) %>% # run model for each variable
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(term=recode(term,
                     fa_global="Factor Score",
                     i_01_rtrade="Pro Free Trade",
                     i_01_risolation="Anti-Isolationism",
                     i_01_immigration5="Increase Immigration Limits",
                     f_01_rdefensejoint="Decrease Defense Spending")) %>%
  arrange(factor(term, levels=c("Factor Score",
                                "Pro Free Trade",
                                "Increase Immigration Limits",
                                "Anti-Isolationism",
                                "Decrease Defense Spending")))
reg2b_pv <- rawdat2b %>%
  filter(sample!="Gen Pop") %>%
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ sample, data = .))) %>% # run model for each variable
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(term=recode(term,
                     fa_global="Factor Score",
                     i_01_rtrade="Pro Free Trade",
                     i_01_risolation="Anti-Isolationism",
                     i_01_immigration5="Increase Immigration Limits",
                     f_01_rdefensejoint="Decrease Defense Spending")) %>%
  arrange(factor(term, levels=c("Factor Score",
                                "Pro Free Trade",
                                "Increase Immigration Limits",
                                "Anti-Isolationism",
                                "Decrease Defense Spending")))

reg2a_pv$Party <- "Republicans"
reg2b_pv$Party <- "Democrats"
reg2_pv <- rbind(reg2a_pv, reg2b_pv)
reg2_pv <- reg2_pv %>%
  rename(
    Group=model,
    Estimate=estimate,
    `P-Value`=p.value) %>%
  select(Party, `P-Value`)

reg2_pv <- as.data.frame(reg2_pv)

reg2_pv <- reg2_pv %>%
  pivot_wider(names_from=c("Party"), values_from=c("P-Value"))


############################################################################################################################################################################
# Table B3. Standard Deviations of Factor Scores by Partisanship and Sample Groupings.
############################################################################################################################################################################

#"All" sample
dat %>% 
  filter((democrat ==1 & republican ==0) | (democrat==0 & republican == 1)) %>%
  group_by(democrat,republican) %>%
  summarize(fa_all = sd(fa_all,na.rm=TRUE),
            fa_global = sd(fa_global,na.rm=TRUE),
            n=n())

#Affluent and Donors Sample
dat %>% 
  filter((democrat ==1 & republican ==0) | (democrat==0 & republican == 1)) %>%
  filter(sample != "Gen Pop") %>%
  group_by(democrat,republican) %>%
  summarize(fa_all = sd(fa_all,na.rm=TRUE),
            fa_global = sd(fa_global,na.rm=TRUE),
            n=n())

#donors only, affluent only, gen pop only
dat %>% group_by(sample,democrat,republican) %>%
  summarize(fa_all = sd(fa_all,na.rm=TRUE),
            fa_global = sd(fa_global,na.rm=TRUE),
            n = n()) %>%
  drop_na() %>%
  filter((democrat ==1 & republican ==0) | (democrat==0 & republican == 1))

############################################################################################
############################################################################################
# APPENDIX C
############################################################################################
############################################################################################

############################################################################################################################################################################
#	Table C1. Unweighted Factor Means and Standard Deviations for Figure 3
############################################################################################################################################################################

reg3 <- rg_fs %>%
  rename(Issue=term,
         Group=model,
         Estimate=estimate,
         `Standard Error`=std.error) %>%
  select(Party, Group, Issues, Estimate, `Standard Error`)
reg3 <- as.data.frame(reg3) %>%
  arrange(Group, Issues, Party)

reg3$`Standard Error` = paste0("(",sprintf(reg3$`Standard Error`, fmt="%.3f"),")")
reg3$Estimate = sprintf(reg3$Estimate, fmt="%.3f")

reg3_ <- reg3 %>%
  pivot_longer(cols=c("Estimate", "Standard Error")) %>%
  pivot_wider(names_from=c("Group","Party"))

reg3_$Issues = as.character(reg3_$Issues)
reg3_$Issues[reg3_$name=="Standard Error"] = " "

reg3_ <- reg3_ %>%
  select("Issues", "Non-Affluent Donor_Democrats","Non-Affluent Donor_Republicans", 
         "Affluent Donor_Democrats", "Affluent Donor_Republicans",
         "Affluent Non-Donor_Democrats","Affluent Non-Donor_Republicans")

kbl(reg3_, "html", 
    col.names = c("", "Democrats", "Republicans", "Democrats", "Republicans", "Democrats", "Republicans")) %>%
  kable_classic(full_width=F, html_font="Times New Roman") %>%
  add_header_above(c(" " = 1, "Non-Affluent Donors" = 2, "Affluent Donors" = 2, "Affluent Non-Donors"=2)) %>%
  cat(., file=paste(outdir_tables, "SI_TableC1_Figure3.html", sep=""))


############################################################################################################################################################################
#	Figure C1. Figure 3 Replication with Respondent Weights
############################################################################################################################################################################

dat_wt <- dat_wt %>%
  mutate(split = ifelse(AffluentDonor==1,"AffluentDonor","Gen Pop"),
         split = ifelse(NonAffluentDonor==1,"NonAffluentDonor",split),
         split = ifelse(AffluentNonDonor==1,"AffluentNonDonor",split),
         split = ifelse(sample==3,"Gen Pop",split))
#############
# Domestic
#############

# Republicans

dat3a_wt <- dat_wt %>%
  filter(republican==1) %>%
  mutate(split=as.factor(split)) %>%
  mutate(split=relevel(split, ref="Gen Pop"))

rawdat3a_wt <- dat3a_wt %>%
  select(split,varlist_general,invpropensitywgt) %>%  
  pivot_longer(names_to = "Variable", cols = varlist_general) %>%
  select(split,Variable,invpropensitywgt,value) %>%
  drop_na()

reg3a_wt <- rawdat3a_wt %>%
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ split, data = ., weights=invpropensitywgt))) %>% # run model for each variable
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(model=recode(model,
                      splitAffluentDonor = "Affluent Donor",
                      splitNonAffluentDonor = "Non-Affluent Donor",
                      splitAffluentNonDonor = "Affluent Non-Donor")) %>%
  arrange(factor(model, levels=c("Affluent Donor","Non-Affluent Donor", "Affluent Non-Donor"))) %>% 
  arrange(factor(term, levels=varlist_general))%>%
  mutate(term=recode(term,
                     fa_all="Factor Score",
                     f_01_minwagejoint="Increase Minimum Wage",
                     i_01_taxes1="Incr. Top Marginal Tax Rate",
                     f_01_tanfjoint="Increase TANF Spending",
                     f_01_sumenvironment="Pro Environmentalism",
                     i_01_health3="Incr. Govt Role in Health Care",
                     f_01_abortionjoint="Fewer Abortion Restrictions",
                     i_01_rguncontrol="More Gun Control")) %>%
  mutate(LCI=estimate-std.error*1.96) %>%
  mutate(UCI=estimate+std.error*1.96)


# Democrats

dat3b_wt <- dat_wt %>%
  filter(democrat==1) %>%
  mutate(split=as.factor(split)) %>%
  mutate(split=relevel(split, ref="Gen Pop"))

rawdat3b_wt <- dat3b_wt %>%
  select(split,varlist_general,invpropensitywgt) %>%  
  pivot_longer(names_to = "Variable", cols = varlist_general) %>%
  select(split,Variable,invpropensitywgt,value) %>%
  drop_na()

reg3b_wt <- rawdat3b_wt %>%
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ split, data = ., weights=invpropensitywgt))) %>% # run model for each variable
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(model=recode(model,
                      splitAffluentDonor = "Affluent Donor",
                      splitNonAffluentDonor = "Non-Affluent Donor",
                      splitAffluentNonDonor = "Affluent Non-Donor")) %>%
  arrange(factor(model, levels=c("Affluent Donor","Non-Affluent Donor", "Affluent Non-Donor"))) %>% 
  arrange(factor(term, levels=varlist_general))%>%
  mutate(term=recode(term,
                     fa_all="Factor Score",
                     f_01_minwagejoint="Increase Minimum Wage",
                     i_01_taxes1="Incr. Top Marginal Tax Rate",
                     f_01_tanfjoint="Increase TANF Spending",
                     f_01_sumenvironment="Pro Environmentalism",
                     i_01_health3="Incr. Govt Role in Health Care",
                     f_01_abortionjoint="Fewer Abortion Restrictions",
                     i_01_rguncontrol="More Gun Control")) %>%
  mutate(LCI=estimate-std.error*1.96) %>%
  mutate(UCI=estimate+std.error*1.96)

# International

# Republicans

dat4a_wt <- dat_wt %>%
  filter(republican==1) %>%
  mutate(split=as.factor(split)) %>%
  mutate(split=relevel(split, ref="Gen Pop"))

rawdat4a_wt <- dat4a_wt %>%
  select(split,varlist_globalist,invpropensitywgt) %>%  
  pivot_longer(names_to = "Variable", cols = varlist_globalist) %>%
  select(split,Variable,invpropensitywgt,value) %>%
  drop_na()

reg4a_wt <- rawdat4a_wt %>%
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ split, data = ., weights=invpropensitywgt))) %>% # run model for each variable
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(model=recode(model,
                      splitAffluentDonor = "Affluent Donor",
                      splitNonAffluentDonor = "Non-Affluent Donor",
                      splitAffluentNonDonor = "Affluent Non-Donor")) %>%
  arrange(factor(model, levels=c("Affluent Donor","Non-Affluent Donor", "Affluent Non-Donor"))) %>% 
  arrange(factor(term, levels=varlist_globalist))%>%
  mutate(term=recode(term,
                     fa_global="Factor Score",
                     i_01_rtrade="Pro Free Trade",
                     i_01_immigration5="Increase Immigration Limits",
                     i_01_risolation="Anti-Isolationism",
                     f_01_rdefensejoint="Decrease Defense Spending")) %>%
  mutate(LCI=estimate-std.error*1.96) %>%
  mutate(UCI=estimate+std.error*1.96)

# Democrats

dat4b_wt <- dat_wt %>%
  filter(democrat==1) %>%
  mutate(split=as.factor(split)) %>%
  mutate(split=relevel(split, ref="Gen Pop")) 


rawdat4b_wt <- dat4b_wt %>%
  select(split,varlist_globalist,invpropensitywgt) %>%  
  pivot_longer(names_to = "Variable", cols = varlist_globalist) %>%
  select(split,Variable,invpropensitywgt,value) %>%
  drop_na()

reg4b_wt <- rawdat4b_wt %>%
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ split, data = ., weights=invpropensitywgt))) %>% # run model for each variable
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(model=recode(model,
                      splitAffluentDonor = "Affluent Donor",
                      splitNonAffluentDonor = "Non-Affluent Donor",
                      splitAffluentNonDonor = "Affluent Non-Donor")) %>%
  arrange(factor(model, levels=c("Affluent Donor","Non-Affluent Donor", "Affluent Non-Donor"))) %>% 
  arrange(factor(term, levels=varlist_globalist))%>%
  mutate(term=recode(term,
                     fa_global="Factor Score",
                     i_01_rtrade="Pro Free Trade",
                     i_01_immigration5="Increase Immigration Limits",
                     i_01_risolation="Anti-Isolationism",
                     f_01_rdefensejoint="Decrease Defense Spending")) %>%
  mutate(LCI=estimate-std.error*1.96) %>%
  mutate(UCI=estimate+std.error*1.96)

nrows <- length(varlist_globalist)
offset <- .2


#       Just Factor Scores - Weighted
reg3a_fs_wt = reg3a_wt %>%
  filter(term=="Factor Score") %>%
  mutate(Party = "Republicans",
         Issues = "Domestic Policy")

reg3a_fs_wt <- bind_rows(reg3a_fs_wt[1,],reg3a_fs_wt[3,],reg3a_fs_wt[2,])

reg3b_fs_wt = reg3b_wt %>%
  filter(term=="Factor Score") %>%
  mutate(Party = "Democrats",
         Issues = "Domestic Policy")

reg3b_fs_wt <- bind_rows(reg3b_fs_wt[1,],reg3b_fs_wt[3,],reg3b_fs_wt[2,])

reg4a_fs_wt = reg4a_wt %>%
  filter(term=="Factor Score") %>%
  mutate(Party = "Republicans",
         Issues = "International")

reg4a_fs_wt <- bind_rows(reg4a_fs_wt[1,],reg4a_fs_wt[3,],reg4a_fs_wt[2,])

reg4b_fs_wt = reg4b_wt %>%
  filter(term=="Factor Score") %>%
  mutate(Party = "Democrats",
         Issues = "International")

reg4b_fs_wt <- bind_rows(reg4b_fs_wt[1,],reg4b_fs_wt[3,],reg4b_fs_wt[2,])

rg_fs_wt = bind_rows(reg4b_fs_wt,reg3b_fs_wt,reg4a_fs_wt,reg3a_fs_wt)

# order 
rg_fs_wt = rg_fs_wt %>%
  mutate(model=factor(model, levels=c("Non-Affluent Donor","Affluent Donor","Affluent Non-Donor"))) %>%
  mutate(Party=factor(Party, levels=c("Republicans", "Democrats"))) %>%
  mutate(Issues=factor(Issues, levels=c("Domestic Policy", "International"))) %>%
  arrange(Party, Issues, model)
yindx <- rev(c(.8,1,1.2,1.8,2,2.2,2.8,3,3.2,3.8,4,4.2))

rg_fs_wt = rg_fs_wt %>%
  mutate(col = if_else(model == "Affluent Non-Donor","GREY","BLACK"),
         plotchar = if_else(model == "Affluent Non-Donor",18,15),
         plotchar = if_else(model == "Affluent Donor",16,plotchar))

pdf(file=paste(outdir_figures,"SI_FigureC1_Figure3_FactorOnly_weighted.pdf", sep=""))
plot(x=c(-.5,.4),y=c(0,5),type="n",axes=FALSE,
     xlab="Difference from Copartisan \n  General Population Average (and 95% CI)",
     ylab="",
     main = "Average Policy Differences By Giving and Affluence")
abline(v=seq(-.3,.3,by=.05),lty=2,col="light grey")
abline(v=0)
axis(1,at=seq(-.3,.3,by=.1),
     labels=c(-.3,-.2,-.1,0,.1,.2,.3))

for(i in 1:nrow(rg_fs_wt)){
  points(x=rg_fs$estimate[i], y=yindx[i],col = rg_fs$col[i], pch=rg_fs$plotchar[i])
  segments(x0 = rg_fs$LCI[i], y0 = yindx[i], x1 = rg_fs$UCI[i], y1 = yindx[i])
}

text(x=-.35,y=1,"International")
text(x=-.35,y=2,"Domestic")
text(x=-.35,y=4,"Domestic")
text(x=-.35,y=3,"International")

text(labels = "More Liberal \n or More Internationalist", x = .2, y = .1,cex=.75)
text(labels = "More Conservative \n or Less Internationalist", x = -.2, y = .1,cex=.75)
text(labels = "More Liberal \n or More Internationalist", x = .2, y = 5,cex=.75)
text(labels = "More Conservative \n or Less Internationalist", x = -.2, y = 5,cex=.75)

text(labels = "Republicans", x = -.45, y = 3.5,srt=90)
text(labels = "Democrats", x = -.45, y = 1.5,srt=90)

legend(-.3,2.75, legend=c("Non-Affluent Donors","Affluent Donors", "Affluent Non-Donors"), 
       col=c("black","black","light grey"), 
       pch=c(15,16,18),
       cex=.7)

dev.off()


############################################################################################################################################################################
# Table C2. Weighted Factor Means and Standard Deviations for Figure C1
############################################################################################################################################################################

reg3_wt <- rg_fs_wt %>%
  rename(Issue=term,
         Group=model,
         Estimate=estimate,
         `Standard Error`=std.error) %>%
  select(Party, Group, Issues, Estimate, `Standard Error`)

reg3_wt <- as.data.frame(reg3_wt) %>%
  arrange(Group, Issues, Party)

reg3_wt$`Standard Error` = paste0("(",sprintf(reg3_wt$`Standard Error`, fmt="%.3f"),")")
reg3_wt$Estimate = sprintf(reg3_wt$Estimate, fmt="%.3f")

reg3_wt_ <- reg3_wt %>%
  pivot_longer(cols=c("Estimate", "Standard Error")) %>%
  pivot_wider(names_from=c("Group","Party"))

reg3_wt_$Issues = as.character(reg3_wt_$Issues)
reg3_wt_$Issues[reg3_wt_$name=="Standard Error"] = " "

reg3_wt_ <- reg3_wt_ %>%
  select("Issues", "Non-Affluent Donor_Democrats","Non-Affluent Donor_Republicans", 
         "Affluent Donor_Democrats", "Affluent Donor_Republicans",
         "Affluent Non-Donor_Democrats","Affluent Non-Donor_Republicans")

kbl(reg3_wt_, "html", 
    col.names = c("", "Democrats", "Republicans", "Democrats", "Republicans", "Democrats", "Republicans")) %>%
  kable_classic(full_width=F, html_font="Times New Roman") %>%
  add_header_above(c(" " = 1, "Non-Affluent Donors" = 2, "Affluent Donors" = 2, "Affluent Non-Donors"=2)) %>%
  cat(., file=paste(outdir_tables, "SI_TableC2_Figure3_weighted.html", sep=""))


############################################################################################################################################################################
# Table C4. Average Differences for Domestic Items by Partisanship, Donor Status, and Affluence. 
############################################################################################################################################################################

reg3a$Party <- "Republicans"
reg3b$Party <- "Democrats"
reg3 <- rbind(reg3a, reg3b)
reg3 <- reg3 %>%
  rename(Issue=term,
         Group=model,
         Estimate=estimate,
         `Standard Error`=std.error) %>%
  select(Party, Issue, Group, Estimate, `Standard Error`)

reg3 <- as.data.frame(reg3) %>%
  arrange(Group, Issue)

reg3$`Standard Error` = paste0("(",sprintf(reg3$`Standard Error`, fmt="%.3f"),")")
reg3$Estimate = sprintf(reg3$Estimate, fmt="%.3f")

reg3_ <- reg3 %>%
  pivot_longer(cols=c("Estimate", "Standard Error")) %>%
  pivot_wider(names_from=c("Group","Party"))

reg3_$Issue[reg3_$name=="Standard Error"] = ""

reg3_ <- reg3_ %>%
  select("Issue", "Non-Affluent Donor_Democrats","Non-Affluent Donor_Republicans", 
         "Affluent Donor_Democrats", "Affluent Donor_Republicans",
         "Affluent Non-Donor_Democrats","Affluent Non-Donor_Republicans")

kbl(reg3_, "html", 
    col.names = c("", "Democrats", "Republicans", "Democrats", "Republicans", "Democrats", "Republicans")) %>%
  kable_classic(full_width=F, html_font="Times New Roman") %>%
  add_header_above(c(" " = 1, "Non-Affluent Donors" = 2, "Affluent Donors" = 2, "Affluent Non-Donors"=2)) %>%
  cat(., file=paste(outdir_tables, "SI_TableC4_figure_A3_weighted.html", sep=""))

############################################################################################################################################################################
# Table C5. Average Differences for International Items by Partisanship, Donor Status, and Affluence. 
############################################################################################################################################################################

reg4a$Party <- "Republicans"
reg4b$Party <- "Democrats"
reg4 <- rbind(reg4a, reg4b)
reg4 <- reg4 %>%
  rename(Issue=term,
         Group=model,
         Estimate=estimate,
         `Standard Error`=std.error) %>%
  select(Party, Issue, Group, Estimate, `Standard Error`)

reg4 <- as.data.frame(reg4) %>%
  arrange(Group, Issue) %>% 
  arrange(factor(Issue, levels=c("Factor Score",
                                "Pro Free Trade",
                                "Increase Immigration Limits",
                                "Anti-Isolationism",
                                "Decrease Defense Spending"))) 

reg4$`Standard Error` = paste0("(",sprintf(reg4$`Standard Error`, fmt="%.3f"),")")
reg4$Estimate = sprintf(reg4$Estimate, fmt="%.3f")

reg4_ <- reg4 %>%
  pivot_longer(cols=c("Estimate", "Standard Error")) %>%
  pivot_wider(names_from=c("Group","Party"))

reg4_$Issue[reg4_$name=="Standard Error"] = ""

reg4_ <- reg4_ %>%
  select("Issue", "Non-Affluent Donor_Democrats","Non-Affluent Donor_Republicans", 
         "Affluent Donor_Democrats", "Affluent Donor_Republicans",
         "Affluent Non-Donor_Democrats","Affluent Non-Donor_Republicans")

kbl(reg4_, "html", 
    col.names = c("", "Democrats", "Republicans", "Democrats", "Republicans", "Democrats", "Republicans")) %>%
  kable_classic(full_width=F, html_font="Times New Roman") %>%
  add_header_above(c(" " = 1, "Non-Affluent Donors" = 2, "Affluent Donors" = 2, "Affluent Non-Donors"=2)) %>%
  cat(., file=paste(outdir_tables, "SI_TableC5_figure_A3.html", sep=""))

############################################################################################
############################################################################################
# APPENDIX D
############################################################################################
############################################################################################


varlist_general <- c("f_01_minwagejoint", 
                     "i_01_taxes1",
                     "f_01_tanfjoint",
                     "f_01_sumenvironment",
                     "i_01_health3",
                     "f_01_abortionjoint",
                     "i_01_rguncontrol"
)
varlist_general_names <- c("Increase Minimum Wage",
                           "Incr. Top Marginal Tax Rate",
                           "Increase TANF Spending",
                           "Pro Environmentalism",
                           "Incr. Govt Role in Health Care",
                           "Fewer Abortion Restrictions",
                           "More Gun Control")

varlist_globalist <- c("i_01_rtrade", 
                       "i_01_risolation",
                       "i_01_immigration5",
                       "f_01_rdefensejoint"
)

varlist_globalist_names <- c("Pro Free Trade",
                             "Anti-Isolationism",
                             "Increase Immigration Limits",
                             "Decrease Defense Spending")



varlist_controls <- c("valdonor",
                      "d_income",
                      "d_networth_total",
                      "d_highpolinterest",
                      "d_religionimp",
                      "d_PostGrad",
                      "d_HSorLess",
                      "union",
                      "d_gender",
                      "r_race_black",
                      "r_race_latino",
                      "r_race_asian",
                      "d_age")

############################################################################################################################################################################
# Table D1. Democrat Domestic Policy Differences: Donors vs. Affluent with Controls
############################################################################################################################################################################

regs_t1_domestic_vars_democrat <- vector('list',7)
for (i in 1:7) {
  d_ <- dat %>% 
    filter(sample!="Gen Pop") %>%
    filter(democrat==1)
  regs_t1_domestic_vars_democrat[[i]] <- 
    lm(as.formula(paste(varlist_general[i], "~", paste(varlist_controls, collapse="+"))), data=d_)
}

r <- regs_t1_domestic_vars_democrat
stargazer(r[1], r[2],r[3],r[4],r[5],r[6],r[7],
          type="html",out=paste(outdir_tables,"SI_TableD1_democrat_domestic.html",sep=""),
          column.labels=varlist_general_names,
          dep.var.caption="",
          omit.stat = c("f", "rsq", "ser"),
          notes = "Dependent variable is the individual policy item normalized to range from [0,1]. OLS coefficients with standard errors in parentheses.",
          dep.var.labels=c("Democrat"),
          covariate.labels=c("Validated Donor",
                             "Income [1,10]",
                             "Net Worth [1,7]",
                             "High political interest",
                             "Religion very important",
                             "Postgraduate degree",
                             "High School or less",
                             "Union Member",
                             "Female",
                             "Black",
                             "Latino/a",
                             "AAPI",
                             "Age")
)

############################################################################################################################################################################
# Table D2. Republican Domestic Policy Differences: Donors vs. Affluent with Controls
############################################################################################################################################################################

regs_t1_domestic_vars_republican <- vector('list',7)
for (i in 1:7) {
  d_ <- dat %>% 
    filter(sample!="Gen Pop") %>%
    filter(republican==1)
  regs_t1_domestic_vars_republican[[i]] <- 
    lm(as.formula(paste(varlist_general[i], "~", paste(varlist_controls, collapse="+"))), data=d_)
}

r <- regs_t1_domestic_vars_republican
stargazer(r[1], r[2],r[3],r[4],r[5],r[6],r[7],
          type="html",out=paste(outdir_tables,"SI_TableD2_republican_domestic.html",sep=""),
          column.labels=varlist_general_names,
          dep.var.labels=c("Republican"),
          omit.stat = c("f", "rsq", "ser"),
          notes = "Dependent variable is the individual policy item normalized to range from [0,1]. OLS coefficients with standard errors in parentheses.",
          dep.var.caption="",
          covariate.labels=c("Validated Donor",
                             "Income [1,10]",
                             "Net Worth [1,7]",
                             "High political interest",
                             "Religion very important",
                             "Postgraduate degree",
                             "High School or less",
                             "Union Member",
                             "Female",
                             "Black",
                             "Latino/a",
                             "AAPI",
                             "Age")
)

############################################################################################################################################################################
# Table D3. Democrat International Policy Differences: Donors vs. Affluent with Controls
############################################################################################################################################################################

regs_t1_international_vars_democrat <- vector('list',4)
for (i in 1:4) {
  d_ <- dat %>% 
    filter(sample!="Gen Pop") %>%
    filter(democrat==1)
  regs_t1_international_vars_democrat[[i]] <- 
    lm(as.formula(paste(varlist_globalist[i], "~", paste(varlist_controls, collapse="+"))), data=d_)
}

r <- regs_t1_international_vars_democrat
stargazer(r[1], r[2],r[3],r[4],
          type="html",out=paste(outdir_tables,"SI_TableD3_democrat_international.html",sep=""),
          column.labels=varlist_globalist_names,
          dep.var.labels=c("Democrat"),
          omit.stat = c("f", "rsq", "ser"),
          notes = "Dependent variable is the individual policy item normalized to range from [0,1]. OLS coefficients with standard errors in parentheses.",
          dep.var.caption="",
          covariate.labels=c("Validated Donor",
                             "Income [1,10]",
                             "Net Worth [1,7]",
                             "High political interest",
                             "Religion very important",
                             "Postgraduate degree",
                             "High School or less",
                             "Union Member",
                             "Female",
                             "Black",
                             "Latino/a",
                             "AAPI",
                             "Age")
)

############################################################################################################################################################################
# Table D4. Republican International Policy Differences: Donors vs. Affluent with Controls
############################################################################################################################################################################

regs_t1_international_vars_republican <- vector('list',4)
for (i in 1:4) {
  d_ <- dat %>% 
    filter(sample!="Gen Pop") %>%
    filter(republican==1)
  regs_t1_international_vars_republican[[i]] <- 
    lm(as.formula(paste(varlist_globalist[i], "~", paste(varlist_controls, collapse="+"))), data=d_)
}


r <- regs_t1_international_vars_republican
stargazer(r[1], r[2],r[3],r[4],
          type="html",out=paste(outdir_tables,"SI_TableD4_republican_international.html",sep=""),
          column.labels=varlist_globalist_names,
          dep.var.labels=c("Republican"),
          dep.var.caption="",
          omit.stat = c("f", "rsq", "ser"),
          notes = "Dependent variable is the individual policy item normalized to range from [0,1]. OLS coefficients with standard errors in parentheses.",
          covariate.labels=c("Validated Donor",
                             "Income [1,10]",
                             "Net Worth [1,7]",
                             "High political interest",
                             "Religion very important",
                             "Postgraduate degree",
                             "High School or less",
                             "Union Member",
                             "Female",
                             "Black",
                             "Latino/a",
                             "AAPI",
                             "Age")
)

############################################################################################################################################################################
# Table D5. Table 2 Robustness: Donors vs. Affluent with Controls including General Population
############################################################################################################################################################################

# domestic
# democrats
reg_t1_domestic_democrat <- dat %>% 
  filter(democrat==1) %>%
  lm(fa_all ~ valdonor + d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age, data=.)
# republicans
reg_t1_domestic_republican <- dat %>% 
  filter(republican==1) %>%
  lm(fa_all ~ valdonor + d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age, data=.)
# international
# democrats
reg_t1_global_democrat <- dat %>% 
  filter(democrat==1) %>%
  lm(fa_global ~ valdonor + d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age, data=.)
# republicans
reg_t1_global_republican <- dat %>% 
  filter(republican==1) %>%
  lm(fa_global ~ valdonor + d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age, data=.)
r1 <- reg_t1_domestic_democrat
r2 <- reg_t1_domestic_republican
r3 <- reg_t1_global_democrat
r4 <- reg_t1_global_republican


stargazer(r1, r2,
          r3, r4,
          type="html",out=paste(outdir_tables,"SI_TableD5_table2_genpop.html",sep=""),
          column.labels=c("Democrat","Republican","Democrat","Republican"),
          dep.var.labels = c("Domestic", "International"),
          dep.var.caption="",
          omit.stat = c("f", "rsq", "ser"),
          notes = "Dependent variables are the factor scales. OLS coefficients with standard errors in parentheses.",
          covariate.labels=c("Validated Donor",
                             "Income [1,10]",
                             "Net Worth [1,7]",
                             "High political interest",
                             "Religion very important",
                             "Postgraduate degree",
                             "High School or less",
                             "Union Member",
                             "Female",
                             "Black",
                             "Latino/a",
                             "AAPI",
                             "Age")
)



############################################################################################################################################################################
# Table D6. Table 2 Robustness:  Donors vs. Affluent with Controls with State Fixed Effects
############################################################################################################################################################################

# domestic
# democrats
reg_t1_domestic_democrat <- dat %>% 
  filter(sample!="Gen Pop") %>%
  filter(democrat==1) %>%
  lm(fa_all ~ valdonor + d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age + as.factor(ts_state), data=.)
# republicans
reg_t1_domestic_republican <- dat %>% 
  filter(sample!="Gen Pop") %>%
  filter(republican==1) %>%
  lm(fa_all ~ valdonor + d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age  + as.factor(ts_state), data=.)
# international
# democrats
reg_t1_global_democrat <- dat %>% 
  filter(sample!="Gen Pop") %>%
  filter(democrat==1) %>%
  lm(fa_global ~ valdonor + d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age  + as.factor(ts_state), data=.)
# republicans
reg_t1_global_republican <- dat %>% 
  filter(sample!="Gen Pop") %>%
  filter(republican==1) %>%
  lm(fa_global ~ valdonor + d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age  + as.factor(ts_state), data=.)
r1 <- reg_t1_domestic_democrat
r2 <- reg_t1_domestic_republican
r3 <- reg_t1_global_democrat
r4 <- reg_t1_global_republican



stargazer(r1, r2,
          r3, r4,
          type="html",out=paste(outdir_tables,"SI_TableD6_MainTable2_stateFE.html", sep=""),
          column.labels=c("Democrat","Republican","Democrat","Republican"),
          dep.var.labels = c("Domestic", "International"),
          dep.var.caption="",
          omit.stat = c("f", "rsq", "ser"),
          omit = c("ts_state"),
          notes = "Dependent variables are the factor scales. OLS coefficients with standard errors in parentheses.",
          covariate.labels=c("Validated Donor",
                             "Income [1,10]",
                             "Net Worth [1,7]",
                             "High political interest",
                             "Religion very important",
                             "Postgraduate degree",
                             "High School or less",
                             "Union Member",
                             "Female",
                             "Black",
                             "Latino/a",
                             "AAPI",
                             "Age")
)

############################################################################################################################################################################
# Table D7. Table 2 Robustness: No Controls other than Giving and Affluence Measures
############################################################################################################################################################################

# domestic
# democrats
reg_t1_domestic_democrat <- dat %>% 
  filter(sample!="Gen Pop") %>%
  filter(democrat==1) %>%
  lm(fa_all ~ valdonor + d_income + d_networth_total, data=.)
# republicans
reg_t1_domestic_republican <- dat %>% 
  filter(sample!="Gen Pop") %>%
  filter(republican==1) %>%
  lm(fa_all ~ valdonor + d_income + d_networth_total, data=.)
# international
# democrats
reg_t1_global_democrat <- dat %>% 
  filter(sample!="Gen Pop") %>%
  filter(democrat==1) %>%
  lm(fa_global ~ valdonor + d_income + d_networth_total, data=.)
# republicans
reg_t1_global_republican <- dat %>% 
  filter(sample!="Gen Pop") %>%
  filter(republican==1) %>%
  lm(fa_global ~ valdonor + d_income + d_networth_total, data=.)
r1 <- reg_t1_domestic_democrat
r2 <- reg_t1_domestic_republican
r3 <- reg_t1_global_democrat
r4 <- reg_t1_global_republican


stargazer(r1, r2,
          r3, r4,
          type="html",out=paste(outdir_tables,"SI_TableD7_MainTable2_NoControls.html", sep=""),
          column.labels=c("Democrat","Republican","Democrat","Republican"),
          dep.var.labels = c("Domestic", "International"),
          omit.stat = c("f", "rsq", "ser"),
          notes = "Dependent variables are the factor scales. OLS coefficients with standard errors in parentheses.",
          dep.var.caption="",
          covariate.labels=c("Validated Donor",
                             "Income [1,10]",
                             "Net Worth [1,7]")
)


############################################################################################
############################################################################################
# APPENDIX E
############################################################################################
############################################################################################

############################################################################################################################################################################
# Table E1.  Table 3 Full Covariate Results
############################################################################################################################################################################

# domestic
# democrats
reg_t2_domestic_democrat <- dat %>% 
  filter(sample!="Gen Pop") %>%
  filter(democrat==1) %>%
  lm(fa_all ~ valdonor + smallamtcont + outstate + pres +
       d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age, data=.)
# republicans
reg_t2_domestic_republican <- dat %>% 
  filter(sample!="Gen Pop") %>%
  filter(republican==1) %>%
  lm(fa_all ~ valdonor + smallamtcont + outstate + pres +
       d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age, data=.)
# international
# democrats
reg_t2_global_democrat <- dat %>% 
  filter(sample!="Gen Pop") %>%
  filter(democrat==1) %>%
  lm(fa_global ~ valdonor + smallamtcont + outstate + pres +
       d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age, data=.)
# republicans
reg_t2_global_republican <- dat %>% 
  filter(sample!="Gen Pop") %>%
  filter(republican==1) %>%
  lm(fa_global ~ valdonor + smallamtcont + outstate + pres +
       d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age, data=.)
r1 <- reg_t2_domestic_democrat
r2 <- reg_t2_domestic_republican
r3 <- reg_t2_global_democrat
r4 <- reg_t2_global_republican



stargazer(r1, r2,
          r3, r4,
          type="html",out=paste(outdir_tables,"SI_TableE1_Table3_controls.html",sep=""),
          column.labels=c("Democrat","Republican","Democrat","Republican"),
          dep.var.labels = c("Domestic", "International"),
          dep.var.caption="",
          omit.stat = c("f", "rsq", "ser"),
          notes = "Dependent variables are the factor scales. OLS coefficients with standard errors in parentheses.",
          covariate.labels=c("Validated Donor",
                             "x $200 or less",
                             "x out-of-state",
                             "x presidential contest",
                             "Income [1,10]",
                             "Net Worth [1,7]",
                             "High political interest",
                             "Religion very important",
                             "Postgraduate degree",
                             "High School or less",
                             "Union Member",
                             "Female",
                             "Black",
                             "Latino/a",
                             "AAPI",
                             "Age")
)


############################################################################################################################################################################
# Table E2. Table 3 Full Covariate Results with State Fixed Effects
############################################################################################################################################################################

# domestic
# democrats
reg_t2_domestic_democrat <- dat %>% 
  filter(sample!="Gen Pop") %>%
  filter(democrat==1) %>%
  lm(fa_all ~ valdonor + smallamtcont + outstate + pres +
       d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age + as.factor(ts_state), data=.)
# republicans
reg_t2_domestic_republican <- dat %>% 
  filter(sample!="Gen Pop") %>%
  filter(republican==1) %>%
  lm(fa_all ~ valdonor + smallamtcont + outstate + pres +
       d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age + as.factor(ts_state), data=.)
# international
# democrats
reg_t2_global_democrat <- dat %>% 
  filter(sample!="Gen Pop") %>%
  filter(democrat==1) %>%
  lm(fa_global ~ valdonor + smallamtcont + outstate + pres +
       d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age + as.factor(ts_state), data=.)
# republicans
reg_t2_global_republican <- dat %>% 
  filter(sample!="Gen Pop") %>%
  filter(republican==1) %>%
  lm(fa_global ~ valdonor + smallamtcont + outstate + pres +
       d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age + as.factor(ts_state), data=.)
r1 <- reg_t2_domestic_democrat
r2 <- reg_t2_domestic_republican
r3 <- reg_t2_global_democrat
r4 <- reg_t2_global_republican


stargazer(r1, r2,
          r3, r4,
          type="html",out=paste(outdir_tables,"SI_TableE2_Table3_controlsFE.html",sep=""),
          column.labels=c("Democrat","Republican","Democrat","Republican"),
          dep.var.labels = c("Domestic", "International"),
          dep.var.caption="",
          omit.stat = c("f", "rsq", "ser"),
          omit = c("ts_state"),
          notes = "Dependent variables are the factor scales. OLS coefficients with standard errors in parentheses.",
          covariate.labels=c("Validated Donor",
                             "x $200 or less",
                             "x out-of-state",
                             "x presidential contest",
                             "Income [1,10]",
                             "Net Worth [1,7]",
                             "High political interest",
                             "Religion very important",
                             "Postgraduate degree",
                             "High School or less",
                             "Union Member",
                             "Female",
                             "Black",
                             "Latino/a",
                             "AAPI",
                             "Age")
)


############################################################################################################################################################################
# Table E3. Table 3 Robustness: Donors vs. Affluent and. Gen Pop by Donor Type with Controls
############################################################################################################################################################################

# domestic
# democrats
reg_t2_domestic_democrat <- dat %>% 
  filter(democrat==1) %>%
  lm(fa_all ~ valdonor + smallamtcont + outstate + pres +
       d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age, data=.)
# republicans
reg_t2_domestic_republican <- dat %>% 
  filter(republican==1) %>%
  lm(fa_all ~ valdonor + smallamtcont + outstate + pres +
       d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age, data=.)
# international
# democrats
reg_t2_global_democrat <- dat %>% 
  filter(democrat==1) %>%
  lm(fa_global ~ valdonor + smallamtcont + outstate + pres +
       d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age, data=.)
# republicans
reg_t2_global_republican <- dat %>% 
  filter(republican==1) %>%
  lm(fa_global ~ valdonor + smallamtcont + outstate + pres +
       d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age, data=.)
r1 <- reg_t2_domestic_democrat
r2 <- reg_t2_domestic_republican
r3 <- reg_t2_global_democrat
r4 <- reg_t2_global_republican


stargazer(r1, r2,
          r3, r4,
          type="html",out=paste(outdir_tables,"SI_TableE3_Table3_controls.html",sep=""),
          column.labels=c("Democrat","Republican","Democrat","Republican"),
          dep.var.labels = c("Domestic", "International"),
          dep.var.caption="",
          omit.stat = c("f", "rsq", "ser"),
          omit = c("ts_state"),
          notes = "Dependent variables are the factor scales. OLS coefficients with standard errors in parentheses.",
          covariate.labels=c("Validated Donor",
                             "x $200 or less",
                             "x out-of-state",
                             "x presidential contest",
                             "Income [1,10]",
                             "Net Worth [1,7]",
                             "High political interest",
                             "Religion very important",
                             "Postgraduate degree",
                             "High School or less",
                             "Union Member",
                             "Female",
                             "Black",
                             "Latino/a",
                             "AAPI",
                             "Age")
)

############################################################################################################################################################################
# Table E4. Table 3 Robustness:  Table 3 Controlling for Contribution Amount & Number of Donations
############################################################################################################################################################################

dat$outdistrict = dat$C1718_HOUSE_INDIST < dat$C1718_HOUSE

# domestic
# democrats
reg_t2_domestic_democrat <- dat %>% 
  filter(sample!="Gen Pop") %>%
  filter(democrat==1) %>%
  lm(fa_all ~ valdonor + #smallamtcont + 
       outstate +
       lnnumcont+lnamtcont+
       pres +
       d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age, data=.)
# republicans
reg_t2_domestic_republican <- dat %>% 
  filter(sample!="Gen Pop") %>%
  filter(republican==1) %>%
  lm(fa_all ~ valdonor + #smallamtcont + 
       outstate +
       lnnumcont+lnamtcont+
       pres +
       d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age, data=.)
# international
# democrats
reg_t2_global_democrat <- dat %>% 
  filter(sample!="Gen Pop") %>%
  filter(democrat==1) %>%
  lm(fa_global ~ valdonor + #smallamtcont + 
       outstate +
       lnnumcont+lnamtcont+
       pres +
       d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age, data=.)
# republicans
reg_t2_global_republican <- dat %>% 
  filter(sample!="Gen Pop") %>%
  filter(republican==1) %>%
  lm(fa_global ~ valdonor + #smallamtcont + 
       outstate +
       lnnumcont+lnamtcont+
       pres +
       d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age, data=.)
r1 <- reg_t2_domestic_democrat
r2 <- reg_t2_domestic_republican
r3 <- reg_t2_global_democrat
r4 <- reg_t2_global_republican
stargazer(r1, r2,
          r3, r4,
          type="html",out=paste(outdir_tables,"SI_TableE4_Table3_contAmtNumb.html",sep=""),
          column.labels=c("Democrat","Republican","Democrat","Republican"),
          dep.var.labels = c("Domestic", "International"),
          dep.var.caption="",
          omit.stat = c("f", "rsq", "ser"),
          omit = c("ts_state"),
          notes = "Dependent variables are the factor scales. OLS coefficients with standard errors in parentheses.",
          covariate.labels=c("Validated Donor",
                             #"Gave $200 or less",
                             "x out-of-state",
                             "x Log Number of Contributions",
                             "x Log Contribution Amount",
                             "x presidential contest",
                             "Income [1,10]",
                             "Net Worth [1,7]",
                             "High political interest",
                             "Religion very important",
                             "Postgraduate degree",
                             "High School or less",
                             "Union Member",
                             "Female",
                             "Black",
                             "Latino/a",
                             "AAPI",
                             "Age")
)

############################################################################################################################################################################
# Table E5. Table 3 Robustness:  Table 3 Controlling for Just Contribution Amount, Not Number of Donations 
############################################################################################################################################################################

# domestic
# democrats
reg_t2_domestic_democrat <- dat %>% 
  filter(sample!="Gen Pop") %>%
  filter(democrat==1) %>%
  lm(fa_all ~ valdonor + #smallamtcont + 
       outstate +
       #lnnumcont+
       lnamtcont+
       pres +
       d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age, data=.)
# republicans
reg_t2_domestic_republican <- dat %>% 
  filter(sample!="Gen Pop") %>%
  filter(republican==1) %>%
  lm(fa_all ~ valdonor + #smallamtcont + 
       outstate +
       #lnnumcont+
       lnamtcont+
       pres +
       d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age, data=.)
# international
# democrats
reg_t2_global_democrat <- dat %>% 
  filter(sample!="Gen Pop") %>%
  filter(democrat==1) %>%
  lm(fa_global ~ valdonor + #smallamtcont + 
       outstate +
       #lnnumcont+
       lnamtcont+
       pres +
       d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age, data=.)
# republicans
reg_t2_global_republican <- dat %>% 
  filter(sample!="Gen Pop") %>%
  filter(republican==1) %>%
  lm(fa_global ~ valdonor + #smallamtcont + 
       outstate +
       #lnnumcont+
       lnamtcont+
       pres +
       d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age, data=.)
r1 <- reg_t2_domestic_democrat
r2 <- reg_t2_domestic_republican
r3 <- reg_t2_global_democrat
r4 <- reg_t2_global_republican


stargazer(r1, r2,
          r3, r4,
          type="html",out=paste(outdir_tables,"SI_TableE5_Table3_outofstate_JustContrAmt.html",sep=""),
          column.labels=c("Democrat","Republican","Democrat","Republican"),
          dep.var.labels = c("Domestic", "International"),
          dep.var.caption="",
          omit.stat = c("f", "rsq", "ser"),
          omit = c("ts_state"),
          notes = "Dependent variables are the factor scales. OLS coefficients with standard errors in parentheses.",
          covariate.labels=c("Validated Donor",
                             #"Gave $200 or less",
                             "x out-of-state",
                             #"Log Number of Contributions",
                             "x Log Contribution Amount",
                             "x 2016 presidential contest",
                             "Income [1,10]",
                             "Net Worth [1,7]",
                             "High political interest",
                             "Religion very important",
                             "Postgraduate degree",
                             "High School or less",
                             "Union Member",
                             "Female",
                             "Black",
                             "Latino/a",
                             "AAPI",
                             "Age")
)


############################################################################################
############################################################################################
# APPENDIX G: see files WeightingScriptDonors.R, WeightingScriptAffluent.R
############################################################################################
############################################################################################



############################################################################################
############################################################################################
# APPENDIX H
############################################################################################
############################################################################################

# Figure H1.  Domestic and International Factor Scores Compared Between and Factor Scores and Samples
a = dat %>% 
  ggplot(aes(x=fa_all,y=fa_global, color = sample)) +
  geom_point() +
  labs(x = "Domestic Factor Score",
       y = "International Factor Score",
       title = "Comparing Relationship Between Domestic and International Issues Domestic Policies Factor Score",   
       color = "Sample") +
  theme_bw()

b = dat %>% 
  ggplot(aes(x=fa_all,y=fa_all_GP, color = sample)) +
  geom_point() +
  labs(x = "Factor Score: All Respondents",
       y = "Factor Score: Using only General Public Respondents",
       title = "Domestic Policy Factor Score",
       color = "Sample") +
  theme_bw()

pdf(file= paste(outdir_figures, "SI_FigureH1_FactorScorePlot.pdf", sep = ""))
grid.arrange(a,b)
dev.off()

############################################################################################################################################################################
# Figure H2.  Distribution of Factor Scores by Sample
############################################################################################################################################################################

a <- dat %>%
  ggplot(aes(x=fa_all,fill=as.factor(sample))) +
  geom_density(alpha=.3) +
  labs(fill="",x="Domestic Factor Score",y="Density",
       title="Distribution of Domestic Factor Score") +
  theme_bw()

b <- dat %>%
  ggplot(aes(x=fa_global,fill=as.factor(sample))) +
  geom_density(alpha=.3) +
  labs(fill="",x="International Factor Score",y="Density",
       title="Distribution of International Factor Score") +
  theme_bw()

pdf(file= paste(outdir_figures, "SI_FigureH2_DistFactorScores.pdf", sep = "")) 
grid.arrange(a,b)
dev.off()





########################################################################################################################################################################################
# Appendix I: Raw policy response averages by party and sample
########################################################################################################################################################################################

#MINIMUM WAGE
min.wage <- dat %>%
  dplyr::select(starts_with("f_minwage"), "sample", "democrat", "republican") %>%
  filter(democrat == 1 | republican == 1) %>%
  filter(!is.na(f_minwagejoint)) %>%
  group_by(f_minwagejoint, sample, republican) %>%
  summarise(count = n()) %>%
  group_by(sample, republican) %>%
  mutate(perc = count / sum(count)) %>%
  ungroup() %>%
  mutate(party = ifelse(republican == 1, "Republican", "Democrat"))


pdf(file="~/Desktop/jop replication/SI_FigureI1_MinimumWage.pdf")
ggplot(min.wage) +
  geom_col(aes(x = f_minwagejoint, y = perc, group = sample, fill = sample), position = "dodge") + 
  scale_x_continuous(breaks = 1:5, labels = rev(c("$15/hour", "$10/hour", "$7.25/hour", "$7.25/hour+\nno local control", "No minimum wage"))) +
  facet_wrap(vars(party)) + 
  theme_minimal() + 
  theme(panel.grid.minor = element_blank(),
        panel.border = element_rect(color = "black", fill = NA, size = 1)) + 
  coord_flip(ylim = c(0, .8)) + 
  labs(y = "Proportion in Favor", x = "", title = "Views on Minimum Wage", subtitle = "Responses by sample and party.", fill = "Sample") +
  guides(fill = guide_legend(reverse = TRUE)) +
  scale_fill_manual(values = c("#d55e00", "#009e73", "#0072b2"))
dev.off()



#IMMIGRATION
i_immigration5 <- dat %>%
  dplyr::select(starts_with("i_immigration5"), "sample", "democrat", "republican") %>%
  filter(democrat == 1 | republican == 1) %>%
  filter(!is.na(i_immigration5)) %>%
  group_by(i_immigration5, sample, republican) %>%
  summarise(count = n()) %>%
  group_by(sample, republican) %>%
  mutate(perc = count / sum(count)) %>%
  ungroup() %>%
  mutate(party = ifelse(republican == 1, "Republican", "Democrat"))

pdf(file="~/Desktop/jop replication/SI_FigureI2_Immigration.pdf")
ggplot(i_immigration5) +
  geom_col(aes(x = i_immigration5, y = perc, group = sample, fill = sample), position = "dodge") + 
  scale_x_discrete(labels = rev(c("Increased a lot", "Increased a little", "Same as now", "Decreased a little", "Decreased a lot"))) +
  facet_wrap(vars(party)) + 
  theme_minimal() + 
  theme(panel.grid.minor = element_blank(),
        panel.border = element_rect(color = "black", fill = NA, size = 1)) + 
  coord_flip(ylim = c(0, 1)) + 
  labs(y = "Proportion in Favor", x = "", title = "Views on Immigration", subtitle = "Responses by sample and party.", fill = "Sample") +
  guides(fill = guide_legend(reverse = TRUE)) +
  scale_fill_manual(values = c("#d55e00", "#009e73", "#0072b2"))
dev.off()



#TRADE
i_rtrade <- dat %>%
  dplyr::select(starts_with("i_rtrade"), "sample", "democrat", "republican") %>%
  filter(democrat == 1 | republican == 1) %>%
  filter(!is.na(i_rtrade)) %>%
  group_by(i_rtrade, sample, republican) %>%
  summarise(count = n()) %>%
  group_by(sample, republican) %>%
  mutate(perc = count / sum(count)) %>%
  ungroup() %>%
  mutate(party = ifelse(republican == 1, "Republican", "Democrat"))

pdf(file="~/Desktop/jop replication/SI_FigureI3_Trade.pdf")
ggplot(i_rtrade) +
  geom_col(aes(x = i_rtrade, y = perc, group = sample, fill = sample), position = "dodge") + 
  scale_x_continuous(breaks = 1:5, labels = c("No trade", "Import tariffs on all goods", "Trade, with job considerations", "Trade, if reciprocal", "Free trade")) +
  facet_wrap(vars(party)) + 
  theme_minimal() + 
  theme(panel.grid.minor = element_blank(),
        panel.border = element_rect(color = "black", fill = NA, size = 1)) + 
  coord_flip(ylim = c(0, 1)) + 
  labs(y = "Proportion in Favor", x = "", title = "Views on International Trade", subtitle = "Responses by sample and party.", fill = "Sample") +
  guides(fill = guide_legend(reverse = TRUE)) +
  scale_fill_manual(values = c("#d55e00", "#009e73", "#0072b2"))
dev.off()



#GUN CONTROL
i_rguncontrol <- dat %>%
  dplyr::select(starts_with("i_rguncontrol"), "sample", "democrat", "republican") %>%
  filter(democrat == 1 | republican == 1) %>%
  filter(!is.na(i_rguncontrol)) %>%
  group_by(i_rguncontrol, sample, republican) %>%
  summarise(count = n()) %>%
  group_by(sample, republican) %>%
  mutate(perc = count / sum(count)) %>%
  ungroup() %>%
  mutate(party = ifelse(republican == 1, "Republican", "Democrat"))

pdf(file="~/Desktop/jop replication/SI_FigureI4_GunControl.pdf")
ggplot(i_rguncontrol) +
  geom_col(aes(x = i_rguncontrol, y = perc, group = sample, fill = sample), position = "dodge") + 
  scale_x_continuous(breaks = 1:4, labels = rev(c("No guns allowed", "No automatic\nall else, background checks", "Any gun\nbackground check", "Any gun\nno background check"))) +
  facet_wrap(vars(party)) + 
  theme_minimal() + 
  theme(panel.grid.minor = element_blank(),
        panel.border = element_rect(color = "black", fill = NA, size = 1)) + 
  coord_flip(ylim = c(0, 1)) + 
  labs(y = "Proportion in Favor", x = "", title = "Views on Gun Control", subtitle = "Responses by sample and party.", fill = "Sample") +
  guides(fill = guide_legend(reverse = TRUE)) +
  scale_fill_manual(values = c("#d55e00", "#009e73", "#0072b2"))
dev.off()



#ABORTION
f_abortionjoint <- dat %>%
  dplyr::select(starts_with("f_abortionjoint"), "sample", "democrat", "republican") %>%
  filter(democrat == 1 | republican == 1) %>%
  filter(!is.na(f_abortionjoint)) %>%
  group_by(f_abortionjoint, sample, republican) %>%
  summarise(count = n()) %>%
  group_by(sample, republican) %>%
  mutate(perc = count / sum(count)) %>%
  ungroup() %>%
  mutate(party = ifelse(republican == 1, "Republican", "Democrat"))

pdf(file="~/Desktop/jop replication/SI_FigureI5_Abortion.pdf")
ggplot(f_abortionjoint) +
  geom_col(aes(x = f_abortionjoint, y = perc, group = sample, fill = sample), position = "dodge") + 
  scale_x_continuous(breaks = 1:4, labels = c("Never permitted", "Rape, incest,\nwoman's life only", "Clear need", "Personal choice")) +
  facet_wrap(vars(party)) + 
  theme_minimal() + 
  theme(panel.grid.minor = element_blank(),
        panel.border = element_rect(color = "black", fill = NA, size = 1)) + 
  coord_flip(ylim = c(0, 1)) + 
  labs(y = "Proportion in Favor", x = "", title = "Views on Abortion", subtitle = "Responses by sample and party.", fill = "Sample") +
  guides(fill = guide_legend(reverse = TRUE)) +
  scale_fill_manual(values = c("#d55e00", "#009e73", "#0072b2"))
dev.off()



#TANF SPENDING
f_tanfjoint <- dat %>%
  dplyr::select(starts_with("f_tanfjoint"), "sample", "democrat", "republican") %>%
  filter(democrat == 1 | republican == 1) %>%
  filter(!is.na(f_tanfjoint)) %>%
  group_by(f_tanfjoint, sample, republican) %>%
  summarise(count = n()) %>%
  group_by(sample, republican) %>%
  mutate(perc = count / sum(count)) %>%
  ungroup() %>%
  mutate(party = ifelse(republican == 1, "Republican", "Democrat"))

pdf(file="~/Desktop/jop replication/SI_FigureI6_TANF.pdf")
ggplot(f_tanfjoint) +
  geom_col(aes(x = f_tanfjoint, y = perc, group = sample, fill = sample), position = "dodge") + 
  scale_x_continuous(breaks = 1:5, labels = rev(c("Remove lifetime cap", "Raise cap to 8 years", "Keep cap at 5 years", "Reduc cap to 2 years", "Eliminate TANF"))) +
  facet_wrap(vars(party)) + 
  theme_minimal() + 
  theme(panel.grid.minor = element_blank(),
        panel.border = element_rect(color = "black", fill = NA, size = 1)) + 
  coord_flip(ylim = c(0, .8)) + 
  labs(y = "Proportion in Favor", x = "", title = "Views on TANF Spending", subtitle = "Responses by sample and party.", fill = "Sample") +
  guides(fill = guide_legend(reverse = TRUE)) +
  scale_fill_manual(values = c("#d55e00", "#009e73", "#0072b2"))
dev.off()


#HEALTH CARE
i_health3 <- dat %>%
  dplyr::select(starts_with("i_health3"), "sample", "democrat", "republican") %>%
  filter(democrat == 1 | republican == 1) %>%
  filter(!is.na(i_health3)) %>%
  group_by(i_health3, sample, republican) %>%
  summarise(count = n()) %>%
  group_by(sample, republican) %>%
  mutate(perc = count / sum(count)) %>%
  ungroup() %>%
  mutate(party = ifelse(republican == 1, "Republican", "Democrat"))


pdf(file="~/Desktop/jop replication/SI_FigureI7_HealthCare.pdf")
ggplot(i_health3) +
  geom_col(aes(x = i_health3, y = perc, group = sample, fill = sample), position = "dodge") + 
  scale_x_continuous(breaks = 1:4, labels = c("No Gov't support", "Some Gov't support", "Gov't health insurance + private", "Govt insurance, no private")) +
  facet_wrap(vars(party)) + 
  theme_minimal() + 
  theme(panel.grid.minor = element_blank(),
        panel.border = element_rect(color = "black", fill = NA, size = 1)) + 
  coord_flip(ylim = c(0, 1)) + 
  labs(y = "Proportion in Favor", x = "", title = "Views on Government Supported Health Care", subtitle = "Responses by sample and party.", fill = "Sample") +
  guides(fill = guide_legend(reverse = TRUE)) +
  scale_fill_manual(values = c("#d55e00", "#009e73", "#0072b2"))
dev.off()



#TOP MARGINAL TAX RATE
tax.rate <- dat %>%
  dplyr::select(starts_with("i_taxes1"), "sample", "democrat", "republican") %>%
  filter(democrat == 1 | republican == 1) %>%
  filter(!is.na(i_taxes1)) %>%
  group_by(i_taxes1, sample, republican) %>%
  summarise(count = n()) %>%
  group_by(sample, republican) %>%
  mutate(perc = count / sum(count)) %>%
  ungroup() %>%
  mutate(party = ifelse(republican == 1, "Republican", "Democrat"))

pdf(file="~/Desktop/jop replication/SI_FigureI8_TaxRate.pdf")
ggplot(tax.rate) +
  geom_col(aes(x = i_taxes1, y = perc, group = sample, fill = sample), position = "dodge") + 
  scale_x_continuous(breaks = 1:5, labels = rev(c("raise to 57%", "raise to 47%", "maintain 37%", "lower to 27%", "lower to 17%"))) +
  facet_wrap(vars(party)) + 
  theme_minimal() + 
  theme(panel.grid.minor = element_blank(),
        panel.border = element_rect(color = "black", fill = NA, size = 1)) + 
  coord_flip(ylim = c(0, .8)) + 
  labs(y = "Proportion in Favor", x = "", title = "Views on Top Marginal Tax Rate", subtitle = "Responses by sample and party.", fill = "Sample") +
  guides(fill = guide_legend(reverse = TRUE)) +
  scale_fill_manual(values = c("#d55e00", "#009e73", "#0072b2"))
dev.off()



########################################################################################################################################################################################
#     Appendix K: Differences By Affluence
########################################################################################################################################################################################

############################################################################################################################################################################
# Table K1 Pooled (Weighted) Differences by Issue with Covariates
############################################################################################################################################################################

# domestic
reg_t1_domestic_nopty <- dat_wt %>% 
  lm(fa_all ~ sample + d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age,
     weights = invpropensitywgt,
     data=.)

reg_t1_domestic <- dat_wt %>% 
  lm(fa_all ~ sample + democrat + republican + d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age,
     weights = invpropensitywgt,
     data=.)

reg_t1_domestic_dem <- dat_wt %>% 
  filter(democrat==1) %>%
  lm(fa_all ~ sample + d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age,
     weights = invpropensitywgt,
     data=.)

reg_t1_domestic_rep <- dat_wt %>% 
  filter(republican==1) %>%
  lm(fa_all ~ sample + d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age,
     weights = invpropensitywgt,
     data=.)

# international
reg_t1_global_nopty <- dat_wt %>% 
  lm(fa_global ~ sample + d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age,
     weights = invpropensitywgt,
     data=.)

reg_t1_global <- dat_wt %>% 
  lm(fa_global ~ sample + democrat + republican + d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age,
     weights = invpropensitywgt,
     data=.)

r1 = reg_t1_domestic_nopty
r2 <- reg_t1_domestic
r3 = reg_t1_global_nopty
r4 <- reg_t1_global
r5 = reg_t1_domestic_dem
r6 = reg_t1_domestic_rep

stargazer(r1, r2, r5, r6, r3, r4,
          type="html",
          out=paste(outdir_tables,"SI_TableK1_genpopaffluent.html",sep=""),
          dep.var.labels = c("Domestic", "International"),
          dep.var.caption="",
          omit.stat = c("f", "rsq", "ser"),
          omit = c("ts_state"),
          notes = "Dependent variables are the factor scales. OLS coefficients with standard errors in parentheses.",
          covariate.labels=c("Donor",
                             "General Population",
                             "Democrat",
                             "Republican",
                             "Income [1,10]",
                             "Net Worth [1,7]",
                             "High political interest",
                             "Religion very important",
                             "Postgraduate degree",
                             "High School or less",
                             "Union Member",
                             "Female",
                             "Black",
                             "Latino/a",
                             "AAPI",
                             "Age")
)


############################################################################################################################################################################
#   Main Table with Interaction for Wealth/Income
#   Appendix Table K2
############################################################################################################################################################################

# domestic
# democrats
reg_t1_domestic_democrat <- dat %>% 
  filter(democrat==1) %>%
  lm(fa_all ~ TS_Donor + TS_Affluent + d_income + d_networth_total + 
       TS_Donor*d_income + TS_Donor*d_networth_total + TS_Affluent*d_income + TS_Affluent*d_networth_total +
       d_highpolinterest + d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age, data=.)
# republicans
reg_t1_domestic_republican <- dat %>% 
  filter(republican==1) %>%
  lm(fa_all ~ TS_Donor + TS_Affluent + d_income + d_networth_total + 
       TS_Donor*d_income + TS_Donor*d_networth_total + TS_Affluent*d_income + TS_Affluent*d_networth_total +
       d_highpolinterest + d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age, data=.)
# international
# democrats
reg_t1_global_democrat <- dat %>% 
  filter(democrat==1) %>%
  lm(fa_global ~ TS_Donor + TS_Affluent + d_income + d_networth_total + 
       TS_Donor*d_income + TS_Donor*d_networth_total + TS_Affluent*d_income + TS_Affluent*d_networth_total +
       d_highpolinterest + d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age, data=.)
# republicans
reg_t1_global_republican <- dat %>% 
  filter(republican==1) %>%
  lm(fa_global ~ TS_Donor + TS_Affluent + d_income + d_networth_total + 
       TS_Donor*d_income + TS_Donor*d_networth_total + TS_Affluent*d_income + TS_Affluent*d_networth_total +
       d_highpolinterest + d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age, data=.)
r1 <- reg_t1_domestic_democrat
r2 <- reg_t1_domestic_republican
r3 <- reg_t1_global_democrat
r4 <- reg_t1_global_republican
stargazer(r1, r2,
          r3, r4,
          type="html",out=paste(outdir_tables,"SI_TableK2.html", sep=""),
          column.labels=c("Democrat","Republican","Democrat","Republican"),
          dep.var.labels = c("Domestic", "International"),
          dep.var.caption="",
          omit.stat = c("f", "rsq", "ser"),
          omit = c("ts_state"),
          notes = "Dependent variables are the factor scales. OLS coefficients with standard errors in parentheses.",
          covariate.labels=c("Donor Sample",
                             "Affluent Sample",
                             "Income [1,10]",
                             "Net Worth [1,7]",
                             "High political interest",
                             "Religion very important",
                             "Postgraduate degree",
                             "High School or less",
                             "Union Member",
                             "Female",
                             "Black",
                             "Latino/a",
                             "AAPI",
                             "Age",
                             "Donor X Income",
                             "Donor X Net Worth",
                             "Affluent X Income",
                             "Affuent X Net Worth")
)


################################################################################################################################################################
#Figure K1
################################################################################################################################################################

dat %>%
  count(sample,ts_income)

dat %>%
  count(sample,ts_wealth)

dat$ts_income_numeric <- as.numeric(gsub("[^0-9]", "", as.character(dat$ts_income)))
dat$ts_income_numeric <- substr(as.character(dat$ts_income_numeric), 1, 7)

dat = dat %>%
  mutate(HighIncome = if_else(ts_income_numeric > 175000,1,0),
         ExtremeIncome = if_else(ts_income_numeric > 250000,1,0))

dat$ts_wealth_numeric <- as.numeric(gsub("[^0-9]", "", as.character(dat$ts_wealth)))
dat$ts_wealth_numeric <- substr(as.character(dat$ts_wealth_numeric), 1, 7)

dat = dat %>%
  mutate(HighWealth = if_else(ts_wealth_numeric >= 2500000,1,0),
         ExtremeWealth = if_else(ts_wealth_numeric >= 5000000,1,0))

table(dat$ts_wealth_numeric,dat$HighWealth)

dat = dat %>%
  mutate(HighAffluent = if_else(HighIncome==1 | HighWealth==1,1,0),
         ExtremeAffluent = if_else(ExtremeIncome ==1 | ExtremeWealth == 1,1,0))

dat %>%
  filter(sample == "Affluent") %>%
  count(HighAffluent) %>%
  drop_na() %>%
  mutate(Pct=n/sum(n))

dat %>%
  filter(sample == "Affluent") %>%
  count(ExtremeAffluent) %>%
  drop_na() %>%
  mutate(Pct=n/sum(n))

dat = dat %>%
  mutate(Affluence = if_else(HighAffluent==1,"Highly Affluent","Affluent"),
         Affluence = if_else(ExtremeAffluent==1,"Extremely Affluent",Affluence))

dat$Affluence = factor(dat$Affluence,
                       levels = c("Affluent","Highly Affluent","Extremely Affluent"))


# Variable list - International Policies
varlist_globalist <- c("fa_all", 
                       "fa_global",
                       "i_01_rtrade", 
                       "i_01_risolation",
                       "i_01_immigration5",
                       "f_01_rdefensejoint"
)

varlist_globalist_names <- c(fa_global="Factor Score",
                             i_01_rtrade="Pro Free Trade",
                             i_01_risolation="Anti-Isolationism",
                             i_01_immigration5="Increase Immigration Limits",
                             f_01_rdefensejoint="Decrease Defense Spending")

varlist_pooled = c(varlist_globalist,varlist_general)

dat_long <- dat %>%
  select(Affluence,sample,varlist_pooled,democrat,republican,d_income,d_networth_total,d_highpolinterest,d_religionimp,d_PostGrad,d_HSorLess,union,d_gender,r_race_black,r_race_latino,r_race_asian,d_age) %>%  
  pivot_longer(names_to = "Variable", cols = varlist_pooled) %>%
  select(Affluence,sample,Variable,value,democrat,republican,d_income,d_networth_total,d_highpolinterest,d_religionimp,d_PostGrad,d_HSorLess,union,d_gender,r_race_black,r_race_latino,r_race_asian,d_age) %>%  
  drop_na()


# Compare Affluence for Affluent:
comp_affluent = dat_long %>%
  filter(sample == "Affluent")  %>%
  group_by(Variable,Affluence) %>% 
  summarize(Avg = mean(value,na.rm=TRUE),
            SD = sd(value,na.rm=TRUE),
            n = n(),
            SE = SD/sqrt(n)) %>%
  mutate(Variable=recode(Variable,
                         fa_all="Domestic Factor Score",
                         f_01_minwagejoint="Increase Minimum Wage",
                         i_01_taxes1="Incr. Top Marginal Tax Rate",
                         f_01_tanfjoint="Increase TANF Spending",
                         f_01_sumenvironment="Pro Environmentalism",
                         i_01_health3="Incr. Govt Role in Health Care",
                         f_01_abortionjoint="Fewer Abortion Restrictions",
                         i_01_rguncontrol="More Gun Control",
                         fa_global="Globalism Factor Score",
                         i_01_rtrade="Pro Free Trade",
                         i_01_risolation="Anti-Isolationism",
                         i_01_immigration5="Increase Immigration Limits",
                         f_01_rdefensejoint="Decrease Defense Spending")) %>%
  mutate(Variable=factor(Variable, levels=c("Domestic Factor Score", 
                                            "Increase Minimum Wage",
                                            "Incr. Top Marginal Tax Rate",
                                            "Increase TANF Spending",
                                            "Pro Environmentalism",
                                            "Incr. Govt Role in Health Care",
                                            "Fewer Abortion Restrictions",
                                            "More Gun Control",
                                            "Globalism Factor Score",
                                            "Pro Free Trade",
                                            "Increase Immigration Limits",
                                            "Anti-Isolationism",
                                            "Decrease Defense Spending"))) %>%
  mutate(LCI=Avg-SE*1.96) %>%
  mutate(UCI=Avg+SE*1.96)

print(comp_affluent,
      n= 260)

pdf(file= paste(outdir_figures, "SI_FigureK1_DonorByAffluenceCompare.pdf", sep = ""))
comp_affluent %>%
  ggplot(aes(x=Avg,y=Variable,fill=factor(Affluence))) +
  geom_bar(stat = "identity",position="dodge") +
  geom_errorbarh(aes(xmin = LCI, xmax = UCI), height = 0.2, position = position_dodge(width = 0.9)) +
  labs(fill = "",
       x = "Average Score (Original Scale)",
       y = "",
       title = "Average Policy Scores Among Affluent Sample by Affluence") +
  theme_bw()
dev.off()


############################################################################################
############################################################################################
# Figure K2
############################################################################################
############################################################################################

# Compare Affluence for Donors

comp_affluent = dat_long %>%
  filter(sample == "Donor")  %>%
  group_by(Variable,Affluence) %>% 
  summarize(Avg = mean(value,na.rm=TRUE),
            SD = sd(value,na.rm=TRUE),
            n = n(),
            SE = SD/sqrt(n)) %>%
  mutate(Variable=recode(Variable,
                         fa_all="Domestic Factor Score",
                         f_01_minwagejoint="Increase Minimum Wage",
                         i_01_taxes1="Incr. Top Marginal Tax Rate",
                         f_01_tanfjoint="Increase TANF Spending",
                         f_01_sumenvironment="Pro Environmentalism",
                         i_01_health3="Incr. Govt Role in Health Care",
                         f_01_abortionjoint="Fewer Abortion Restrictions",
                         i_01_rguncontrol="More Gun Control",
                         fa_global="Globalism Factor Score",
                         i_01_rtrade="Pro Free Trade",
                         i_01_risolation="Anti-Isolationism",
                         i_01_immigration5="Increase Immigration Limits",
                         f_01_rdefensejoint="Decrease Defense Spending")) %>%
  mutate(Variable=factor(Variable, levels=c("Domestic Factor Score", 
                                            "Increase Minimum Wage",
                                            "Incr. Top Marginal Tax Rate",
                                            "Increase TANF Spending",
                                            "Pro Environmentalism",
                                            "Incr. Govt Role in Health Care",
                                            "Fewer Abortion Restrictions",
                                            "More Gun Control",
                                            "Globalism Factor Score",
                                            "Pro Free Trade",
                                            "Increase Immigration Limits",
                                            "Anti-Isolationism",
                                            "Decrease Defense Spending"))) %>%
  mutate(LCI=Avg-SE*1.96) %>%
  mutate(UCI=Avg+SE*1.96)

print(comp_affluent,
      n= 260)

pdf(file= paste(outdir_figures, "SI_FigureK2_DonorsByAffluenceCompare.pdf", sep = ""))
comp_affluent %>%
  ggplot(aes(x=Avg,y=Variable,fill=factor(Affluence))) +
  geom_bar(stat = "identity",position="dodge") +
  geom_errorbarh(aes(xmin = LCI, xmax = UCI), height = 0.2, position = position_dodge(width = 0.9)) +
  labs(fill = "",
       x = "Average Score (Original Scale)",
       y = "",
       title = "Average Policy Scores Among Donors by Affluence") +
  theme_bw()
dev.off()



################################################################################################################################################################
#Figure K3
################################################################################################################################################################

# Use Inverse Propensity score for weights
# Drop data with missing weights (i.e., missing voter file demographics (but we coded missing as a category in weighting))

dat_wt <- dat %>%
  drop_na(invpropensitywgt) %>%
  mutate(sample=as.factor(sample)) %>%
  mutate(sample=relevel(sample, ref="Gen Pop"))


# Variable list - General Policies - must be in same order!
varlist_general <- c("fa_all",
                     "f_01_minwagejoint", 
                     "i_01_taxes1",
                     "f_01_tanfjoint",
                     "f_01_sumenvironment",
                     "i_01_health3",
                     "f_01_abortionjoint",
                     "i_01_rguncontrol"
)
varlist_general_names <- c(fa_all="Factor Score",
                           f_01_minwagejoint="Increase Minimum Wage",
                           i_01_taxes1="Incr. Top Marginal Tax Rate",
                           f_01_tanfjoint="Increase TANF Spending",
                           f_01_sumenvironment="Pro Environmentalism",
                           i_01_health3="Incr. Govt Role in Health Care",
                           f_01_abortionjoint="Fewer Abortion Restrictions",
                           i_01_rguncontrol="More Gun Control")


reg_t1_domestic_nopty <- dat_wt %>% 
  lm(fa_all ~ sample + d_income + d_networth_total+ d_highpolinterest + 
       d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
       r_race_black + r_race_latino + r_race_asian + d_age,
     weights = invpropensitywgt,
     data=.)


varlist_pooled_names = c(varlist_globalist_names,varlist_general_names)

varlist_pooled_names[1] = "Globalism Factor Score"
varlist_pooled_names[6] = "Domestic Factor Score"

dat_wt_long <- dat_wt %>%
  select(sample,varlist_pooled,invpropensitywgt) %>%  
  pivot_longer(names_to = "Variable", cols = varlist_pooled) %>%
  select(sample,Variable,value,invpropensitywgt ) %>%
  drop_na()

  
# Note - should use robust SE

reg_pooled <- dat_wt_long %>%
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ sample,
                    weights = invpropensitywgt,
                    data = .))) %>% # run model for each variable
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(model=recode(model,
                      sampleAffluent = "Affluent",
                      sampleDonor = "Donor")) %>%
  arrange(factor(model, levels=c("Donor","Affluent"))) %>% 
  arrange(factor(term, levels=varlist_general))%>%
  mutate(model=factor(model, levels=c("Donor", "Affluent"))) %>%
  mutate(term=recode(term,
                     fa_all="Domestic Factor Score",
                     f_01_minwagejoint="Increase Minimum Wage",
                     i_01_taxes1="Incr. Top Marginal Tax Rate",
                     f_01_tanfjoint="Increase TANF Spending",
                     f_01_sumenvironment="Pro Environmentalism",
                     i_01_health3="Incr. Govt Role in Health Care",
                     f_01_abortionjoint="Fewer Abortion Restrictions",
                     i_01_rguncontrol="More Gun Control",
                     fa_global="Globalism Factor Score",
                     i_01_rtrade="Pro Free Trade",
                     i_01_risolation="Anti-Isolationism",
                     i_01_immigration5="Increase Immigration Limits",
                     f_01_rdefensejoint="Decrease Defense Spending")) %>%
  mutate(term=factor(term, levels=c("Domestic Factor Score", 
                                    "Increase Minimum Wage",
                                    "Incr. Top Marginal Tax Rate",
                                    "Increase TANF Spending",
                                    "Pro Environmentalism",
                                    "Incr. Govt Role in Health Care",
                                    "Fewer Abortion Restrictions",
                                    "More Gun Control",
                                    "Globalism Factor Score",
                                    "Pro Free Trade",
                                    "Increase Immigration Limits",
                                    "Anti-Isolationism",
                                    "Decrease Defense Spending"))) %>%
  mutate(LCI=estimate-std.error*1.96) %>%
  mutate(UCI=estimate+std.error*1.96)

##############
# Now Make figure
##############

nrows <- length(varlist_pooled)
offset <- .2
textsize = .6

pdf(file= paste(outdir_figures, "/SI_FigureK3_PooledAVGDifferences.pdf", sep = ""))

plot(x=c(-.12,.3),y=c(1,length(varlist_pooled)+1),type="n",axes=FALSE,
     xlab="Difference from \n  General Population Mean (and 95% CI)",
     ylab="",
     main = "Average Policy Differences \n Between the General Public and Donors or Affluent")
abline(v=seq(-.1,.3,by=.05),lty=2,col="light grey")
abline(v=0)
axis(1,at=seq(-.1,.3,by=.05),
     labels=c(-.1,-.05,0,.05,.1,.15,.2,.25,.3))

for(i in 1: length(varlist_pooled)){
  donor_row <- reg_pooled %>%
    filter(term == varlist_pooled_names[varlist_pooled[nrows-i+1]], model == "Donor")
  affluent_row <- reg_pooled %>%
    filter(term == varlist_pooled_names[varlist_pooled[nrows-i+1]], model == "Affluent")
  
 # text(x=0.2,y=i+1,labels=round(donor_row$statistic,digits=2),cex=.75)
  
  # point estimate
  points(x=donor_row$estimate, y=i+1+offset,pch=16)
  points(x=affluent_row$estimate, y=i+1-offset, col = "GREY", pch = 18)
  
  segments(x0 = donor_row$LCI, y0 = i+1+offset, x1 = donor_row$UCI, y1 = i+1+offset)
  segments(x0 = affluent_row$LCI, y0 = i+1-offset, x1 = affluent_row$UCI, y1 = i+1-offset, col = "grey")
}

text(labels=rev(varlist_pooled_names),x=rep(-.12,times=length(varlist_pooled_names)),
     y=1+seq(1,length(varlist_pooled_names)),cex=textsize,pos=4)

text(labels = "Domestic", x = -.12, y = 5.5,srt=90)
text(labels = "Globalism", x = -.12, y = 11.5,srt=90)
abline(h=9.5,lty=2)

legend(.25,4, legend=c("Donors", "Affluent"), col=c("black","light grey"), pch=c(16,18),cex=.75)
dev.off()


################################################################################################################################################################
#Figure K4
################################################################################################################################################################

dat_wt_long <- dat_wt %>%
  select(sample,varlist_pooled,invpropensitywgt,democrat,republican,d_income,d_networth_total,d_highpolinterest,d_religionimp,d_PostGrad,d_HSorLess,union,d_gender,r_race_black,r_race_latino,r_race_asian,d_age) %>%  
  pivot_longer(names_to = "Variable", cols = varlist_pooled) %>%
  select(sample,Variable,value,invpropensitywgt,democrat,republican,d_income,d_networth_total,d_highpolinterest,d_religionimp,d_PostGrad,d_HSorLess,union,d_gender,r_race_black,r_race_latino,r_race_asian,d_age) %>%  
  drop_na()

reg_pooled_covs <- dat_wt_long %>%
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ sample + d_income + d_networth_total+ d_highpolinterest + 
                      d_religionimp + d_PostGrad + d_HSorLess + union + d_gender + 
                      r_race_black + r_race_latino + r_race_asian + d_age,
                    weights = invpropensitywgt,
                    data = .))) %>% # run model for each variable
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model == "sampleAffluent" | model == "sampleDonor") %>%
  mutate(model=recode(model,
                      sampleAffluent = "Affluent",
                      sampleDonor = "Donor")) %>%
  arrange(factor(model, levels=c("Donor","Affluent"))) %>% 
  arrange(factor(term, levels=varlist_general))%>%
  mutate(model=factor(model, levels=c("Donor", "Affluent"))) %>%
  mutate(term=recode(term,
                     fa_all="Domestic Factor Score",
                     f_01_minwagejoint="Increase Minimum Wage",
                     i_01_taxes1="Incr. Top Marginal Tax Rate",
                     f_01_tanfjoint="Increase TANF Spending",
                     f_01_sumenvironment="Pro Environmentalism",
                     i_01_health3="Incr. Govt Role in Health Care",
                     f_01_abortionjoint="Fewer Abortion Restrictions",
                     i_01_rguncontrol="More Gun Control",
                     fa_global="Globalism Factor Score",
                     i_01_rtrade="Pro Free Trade",
                     i_01_risolation="Anti-Isolationism",
                     i_01_immigration5="Increase Immigration Limits",
                     f_01_rdefensejoint="Decrease Defense Spending")) %>%
  mutate(term=factor(term, levels=c("Domestic Factor Score", 
                                    "Increase Minimum Wage",
                                    "Incr. Top Marginal Tax Rate",
                                    "Increase TANF Spending",
                                    "Pro Environmentalism",
                                    "Incr. Govt Role in Health Care",
                                    "Fewer Abortion Restrictions",
                                    "More Gun Control",
                                    "Globalism Factor Score",
                                    "Pro Free Trade",
                                    "Increase Immigration Limits",
                                    "Anti-Isolationism",
                                    "Decrease Defense Spending"))) %>%
  mutate(LCI=estimate-std.error*1.96) %>%
  mutate(UCI=estimate+std.error*1.96)


##############
# Now Make figure
##############

nrows <- length(varlist_pooled)
offset <- .2

pdf(file= paste(outdir_figures, "/SI_FigureK4_PooledDifferencesAffluentGenPop_covs.pdf", sep = ""))

plot(x=c(-.12,.4),y=c(1,length(varlist_pooled)+1),type="n",axes=FALSE,
     xlab="Difference from \n  General Population Mean (and 95% CI)",
     ylab="",
     main = "Average Policy Differences \n Between the General Public and Donors or Affluent")
abline(v=seq(-.1,.4,by=.05),lty=2,col="light grey")
abline(v=0)
axis(1,at=seq(-.1,.4,by=.05),
     labels=c(-.1,-.05,0,.05,.1,.15,.2,.25,.3,.35,.4))

for(i in 1: length(varlist_pooled)){
  donor_row <- reg_pooled_covs %>%
    filter(term == varlist_pooled_names[varlist_pooled[nrows-i+1]], model == "Donor")
  affluent_row <- reg_pooled_covs %>%
    filter(term == varlist_pooled_names[varlist_pooled[nrows-i+1]], model == "Affluent")

  # point estimate
  points(x=donor_row$estimate, y=i+1+offset,pch=16)
  points(x=affluent_row$estimate, y=i+1-offset, col = "GREY", pch = 18)
  
  segments(x0 = donor_row$LCI, y0 = i+1+offset, x1 = donor_row$UCI, y1 = i+1+offset)
  segments(x0 = affluent_row$LCI, y0 = i+1-offset, x1 = affluent_row$UCI, y1 = i+1-offset, col = "grey")
}

text(labels=rev(varlist_pooled_names),x=rep(-.12,times=length(varlist_pooled_names)),
     y=1+seq(1,length(varlist_pooled_names)),cex=textsize,pos=4)

text(labels = "Domestic", x = -.12, y = 5.5,srt=90)
text(labels = "Globalism", x = -.12, y = 11.5,srt=90)
abline(h=9.5,lty=2)

legend(.25,4, legend=c("Donors", "Affluent"), col=c("black","light grey"), pch=c(16,18),cex=.75)
dev.off()







################################################################################
################################################################################
#  APPENDIX L:  Figure L1 Donor Weighted Difference
#################################################################################
################################################################################


dat_long_donor <- dat %>%
  filter(sample == "Donor") %>%
  select(varlist_pooled,amtcont,democrat) %>%  
  drop_na() %>%
  mutate(PctCont = 100*amtcont/sum(amtcont)) %>%
  pivot_longer(names_to = "Variable", cols = varlist_pooled) 

comp_donor_uw = dat_long_donor %>%
  group_by(Variable,democrat) %>% 
  summarize(Avg = mean(value,na.rm=TRUE)) %>%
  mutate(Variable=recode(Variable,
                         fa_all="Domestic Factor Score",
                         f_01_minwagejoint="Increase Minimum Wage",
                         i_01_taxes1="Incr. Top Marginal Tax Rate",
                         f_01_tanfjoint="Increase TANF Spending",
                         f_01_sumenvironment="Pro Environmentalism",
                         i_01_health3="Incr. Govt Role in Health Care",
                         f_01_abortionjoint="Fewer Abortion Restrictions",
                         i_01_rguncontrol="More Gun Control",
                         fa_global="Globalism Factor Score",
                         i_01_rtrade="Pro Free Trade",
                         i_01_risolation="Anti-Isolationism",
                         i_01_immigration5="Increase Immigration Limits",
                         f_01_rdefensejoint="Decrease Defense Spending")) %>%
  mutate(Variable=factor(Variable, levels=c("Domestic Factor Score", 
                                            "Increase Minimum Wage",
                                            "Incr. Top Marginal Tax Rate",
                                            "Increase TANF Spending",
                                            "Pro Environmentalism",
                                            "Incr. Govt Role in Health Care",
                                            "Fewer Abortion Restrictions",
                                            "More Gun Control",
                                            "Globalism Factor Score",
                                            "Pro Free Trade",
                                            "Increase Immigration Limits",
                                            "Anti-Isolationism",
                                            "Decrease Defense Spending"))) %>%
  mutate(Average = "Equally Weighted")

comp_donor_w = dat_long_donor %>%
  group_by(Variable,democrat) %>% 
  summarize(Avg = weighted.mean(value,w=PctCont,na.rm=TRUE)) %>%
  mutate(Variable=recode(Variable,
                         fa_all="Domestic Factor Score",
                         f_01_minwagejoint="Increase Minimum Wage",
                         i_01_taxes1="Incr. Top Marginal Tax Rate",
                         f_01_tanfjoint="Increase TANF Spending",
                         f_01_sumenvironment="Pro Environmentalism",
                         i_01_health3="Incr. Govt Role in Health Care",
                         f_01_abortionjoint="Fewer Abortion Restrictions",
                         i_01_rguncontrol="More Gun Control",
                         fa_global="Globalism Factor Score",
                         i_01_rtrade="Pro Free Trade",
                         i_01_risolation="Anti-Isolationism",
                         i_01_immigration5="Increase Immigration Limits",
                         f_01_rdefensejoint="Decrease Defense Spending")) %>%
  mutate(Variable=factor(Variable, levels=c("Domestic Factor Score", 
                                            "Increase Minimum Wage",
                                            "Incr. Top Marginal Tax Rate",
                                            "Increase TANF Spending",
                                            "Pro Environmentalism",
                                            "Incr. Govt Role in Health Care",
                                            "Fewer Abortion Restrictions",
                                            "More Gun Control",
                                            "Globalism Factor Score",
                                            "Pro Free Trade",
                                            "Increase Immigration Limits",
                                            "Anti-Isolationism",
                                            "Decrease Defense Spending"))) %>%
  mutate(Average = "Contribution Weighted")


comp_donor = bind_rows(comp_donor_w,comp_donor_uw)

comp_donor = comp_donor %>%
  mutate(party = if_else(democrat==1,"Democrat","Republican"))


pdf(file= paste(outdir_figures, "SI_FigureL1_ContributionWeightedCompare.pdf", sep = ""))
comp_donor %>%
  ggplot(aes(x=Avg,y=Variable,fill=factor(Average))) +
  geom_bar(stat = "identity",position="dodge") +
  labs(fill = "",
       x = "Average Score",
       y = "",
       title = "Average Policy Scores",
       subtitle = "Contribution Weights based on Proportion of Total Giving") +
  theme_bw() +
  facet_wrap(~party)
dev.off()


########################################################################################################################################################################################
# Rescale all variables to be mean 0 standard deviation of 1 ########################################################################################################################################################################################

##############################################################################################################
#Figure L2: Differences in Donor, Affluent, and General Population Policy Views on Domestic Issues by Party
##############################################################################################################

# Variable list - General Policies - must be in same order!
varlist_general <- c("fa_all",
                     "f_01_minwagejoint", 
                     "i_01_taxes1",
                     "f_01_tanfjoint",
                     "f_01_sumenvironment",
                     "i_01_health3",
                     "f_01_abortionjoint",
                     "i_01_rguncontrol"
)
varlist_names <- c(fa_all="Factor Score",
                   f_01_minwagejoint="Increase Minimum Wage",
                   i_01_taxes1="Incr. Top Marginal Tax Rate",
                   f_01_tanfjoint="Increase TANF Spending",
                   f_01_sumenvironment="Pro Environmentalism",
                   i_01_health3="Incr. Govt Role in Health Care",
                   f_01_abortionjoint="Fewer Abortion Restrictions",
                   i_01_rguncontrol="More Gun Control")

textsize <- .6

# Republicans Regression
dat1a <- dat %>%
  filter(republican==1) %>%
  mutate(sample=as.factor(sample)) %>%
  mutate(sample=relevel(sample, ref="Gen Pop"))

rawdat1a <- dat1a %>%
  dplyr::select(sample,varlist_general) %>%  
  pivot_longer(names_to = "Variable", cols = varlist_general) %>%
  mutate(value = scale(value)) %>%
  dplyr::select(sample,Variable,value) %>%
  drop_na()

reg1a <- rawdat1a %>%
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ sample, data = .))) %>% # run model for each variable
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(model=recode(model,
                      sampleAffluent = "Affluent",
                      sampleDonor = "Donor")) %>%
  arrange(factor(model, levels=c("Donor","Affluent"))) %>% 
  arrange(factor(term, levels=varlist_general))%>%
  mutate(model=factor(model, levels=c("Donor", "Affluent"))) %>%
  mutate(term=recode(term,
                     fa_all="Factor Score",
                     f_01_minwagejoint="Increase Minimum Wage",
                     i_01_taxes1="Incr. Top Marginal Tax Rate",
                     f_01_tanfjoint="Increase TANF Spending",
                     f_01_sumenvironment="Pro Environmentalism",
                     i_01_health3="Incr. Govt Role in Health Care",
                     f_01_abortionjoint="Fewer Abortion Restrictions",
                     i_01_rguncontrol="More Gun Control")) %>%
  mutate(term=factor(term, levels=c("Factor Score", 
                                    "Increase Minimum Wage",
                                    "Incr. Top Marginal Tax Rate",
                                    "Increase TANF Spending",
                                    "Pro Environmentalism",
                                    "Incr. Govt Role in Health Care",
                                    "Fewer Abortion Restrictions",
                                    "More Gun Control"))) %>%
  mutate(LCI=estimate-std.error*1.96) %>%
  mutate(UCI=estimate+std.error*1.96)

diff1a <- rawdat1a %>%
  filter(sample == "Donor" | sample == "Affluent") %>%
  mutate(sample=relevel(sample, ref="Affluent")) %>% 
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ sample, data = .))) %>%
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(tstat = format(abs(round(statistic,digits=2)),nsmall=2)) %>%
  mutate(term=recode(term,
                     fa_all="Factor Score",
                     f_01_minwagejoint="Increase Minimum Wage",
                     i_01_taxes1="Incr. Top Marginal Tax Rate",
                     f_01_tanfjoint="Increase TANF Spending",
                     f_01_sumenvironment="Pro Environmentalism",
                     i_01_health3="Incr. Govt Role in Health Care",
                     f_01_abortionjoint="Fewer Abortion Restrictions",
                     i_01_rguncontrol="More Gun Control")) %>%
  dplyr::select(term,tstat)

reg1a = left_join(reg1a,diff1a)

reg1a_daonly <- rawdat1a %>%
  filter(sample != "Gen Pop") %>%
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ sample, data = .))) %>% # run model for each variable
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(model=recode(model,
                      sampleDonor = "Difference")) %>%
  arrange(factor(term, levels=varlist_general)) %>%
  #  mutate(model=factor(model, levels=c("Donor", "Affluent"))) %>%
  mutate(term=recode(term,
                     fa_all="Factor Score",
                     f_01_minwagejoint="Increase Minimum Wage",
                     i_01_taxes1="Incr. Top Marginal Tax Rate",
                     f_01_tanfjoint="Increase TANF Spending",
                     f_01_sumenvironment="Pro Environmentalism",
                     i_01_health3="Incr. Govt Role in Health Care",
                     f_01_abortionjoint="Fewer Abortion Restrictions",
                     i_01_rguncontrol="More Gun Control")) %>%
  mutate(term=factor(term, levels=c("Factor Score", 
                                    "Increase Minimum Wage",
                                    "Incr. Top Marginal Tax Rate",
                                    "Increase TANF Spending",
                                    "Pro Environmentalism",
                                    "Incr. Govt Role in Health Care",
                                    "Fewer Abortion Restrictions",
                                    "More Gun Control"))) %>%
  mutate(LCI=estimate-std.error*1.96) %>%
  mutate(UCI=estimate+std.error*1.96)

# Democrats Regression
dat1b <- dat %>%
  filter(democrat==1) %>%
  mutate(sample=as.factor(sample)) %>%
  mutate(sample=relevel(sample, ref="Gen Pop"))

rawdat1b <- dat1b %>%
  dplyr::select(sample,varlist_general) %>%  
  pivot_longer(names_to = "Variable", cols = varlist_general) %>%
  mutate(value = scale(value)) %>%
  dplyr::select(sample,Variable,value) %>%
  drop_na()

reg1b <- rawdat1b %>%
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ sample, data = .))) %>% # run model for each variable
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(model=recode(model,
                      sampleAffluent = "Affluent",
                      sampleDonor = "Donor")) %>%
  arrange(factor(model, levels=c("Donor","Affluent"))) %>% 
  arrange(factor(term, levels=varlist_general))%>%
  mutate(model=factor(model, levels=c("Donor", "Affluent"))) %>%
  mutate(term=recode(term,
                     fa_all="Factor Score",
                     f_01_minwagejoint="Increase Minimum Wage",
                     i_01_taxes1="Incr. Top Marginal Tax Rate",
                     f_01_tanfjoint="Increase TANF Spending",
                     f_01_sumenvironment="Pro Environmentalism",
                     i_01_health3="Incr. Govt Role in Health Care",
                     f_01_abortionjoint="Fewer Abortion Restrictions",
                     i_01_rguncontrol="More Gun Control")) %>%
  mutate(term=factor(term, levels=c("Factor Score", 
                                    "Increase Minimum Wage",
                                    "Incr. Top Marginal Tax Rate",
                                    "Increase TANF Spending",
                                    "Pro Environmentalism",
                                    "Incr. Govt Role in Health Care",
                                    "Fewer Abortion Restrictions",
                                    "More Gun Control"))) %>%
  mutate(LCI=estimate-std.error*1.96) %>%
  mutate(UCI=estimate+std.error*1.96)

diff1b <- rawdat1b %>%
  filter(sample == "Donor" | sample == "Affluent") %>%
  mutate(sample=relevel(sample, ref="Affluent")) %>% 
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ sample, data = .))) %>%
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(tstat = format(abs(round(statistic,digits=2)),nsmall=2)) %>%
  mutate(term=recode(term,
                     fa_all="Factor Score",
                     f_01_minwagejoint="Increase Minimum Wage",
                     i_01_taxes1="Incr. Top Marginal Tax Rate",
                     f_01_tanfjoint="Increase TANF Spending",
                     f_01_sumenvironment="Pro Environmentalism",
                     i_01_health3="Incr. Govt Role in Health Care",
                     f_01_abortionjoint="Fewer Abortion Restrictions",
                     i_01_rguncontrol="More Gun Control")) %>%
  dplyr::select(term,tstat)

reg1b = left_join(reg1b,diff1b)

reg1b_daonly <- rawdat1b %>%
  filter(sample != "Gen Pop") %>%
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ sample, data = .))) %>% # run model for each variable
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(model=recode(model,
                      sampleDonor = "Difference")) %>%
  arrange(factor(term, levels=varlist_general)) %>%
  #  mutate(model=factor(model, levels=c("Donor", "Affluent"))) %>%
  mutate(term=recode(term,
                     fa_all="Factor Score",
                     f_01_minwagejoint="Increase Minimum Wage",
                     i_01_taxes1="Incr. Top Marginal Tax Rate",
                     f_01_tanfjoint="Increase TANF Spending",
                     f_01_sumenvironment="Pro Environmentalism",
                     i_01_health3="Incr. Govt Role in Health Care",
                     f_01_abortionjoint="Fewer Abortion Restrictions",
                     i_01_rguncontrol="More Gun Control")) %>%
  mutate(term=factor(term, levels=c("Factor Score", 
                                    "Increase Minimum Wage",
                                    "Incr. Top Marginal Tax Rate",
                                    "Increase TANF Spending",
                                    "Pro Environmentalism",
                                    "Incr. Govt Role in Health Care",
                                    "Fewer Abortion Restrictions",
                                    "More Gun Control"))) %>%
  mutate(LCI=estimate-std.error*1.96) %>%
  mutate(UCI=estimate+std.error*1.96)

##############
# Now Make figure
##############

nrows <- length(varlist_general)
offset <- .2

pdf(file= paste(outdir_figures, "SI_FigureL2_MAIN_Figure1_Scaled.pdf", sep = ""))

plot(x=c(-.5,.5),y=c(1,2*length(varlist_general)+5),type="n",axes=FALSE,
     xlab="Difference from Copartisan \n  General Population Mean (and 95% CI)",
     ylab="",
     main = "Average Policy Differences \n Among Donors, Affluent, and General Public")
abline(v=seq(-.3,.5,by=.05),lty=2,col="light grey")
abline(v=0)
axis(1,at=seq(-.3,.5,by=.05),
     labels=c(-.3,-.25,-.2,-.15,-.1,-.05,0,.05,.1,.15,.2,.25,.3,.35,.4,.45,.5))

# democrats
for(i in 1: length(varlist_general)){
  donor_row <- reg1b %>%
    filter(term == varlist_names[varlist_general[nrows-i+1]], model == "Donor")
  affluent_row <- reg1b %>%
    filter(term == varlist_names[varlist_general[nrows-i+1]], model == "Affluent")
  
  text(x=0.5,y=i+1,labels=donor_row$tstat,cex=.75)
  
  # point estimate
  points(x=donor_row$estimate, y=i+1+offset,pch=16)
  points(x=affluent_row$estimate, y=i+1-offset, col = "GREY", pch = 18)
  
  segments(x0 = donor_row$LCI, y0 = i+1+offset, x1 = donor_row$UCI, y1 = i+1+offset)
  segments(x0 = affluent_row$LCI, y0 = i+1-offset, x1 = affluent_row$UCI, y1 = i+1-offset, col = "grey")
}

text(labels=rev(varlist_names),x=rep(-.4,times=length(varlist_general)),
     y=1+seq(1,length(varlist_general)),cex=textsize,pos=4)
text(labels = "Democrats", x = -.4, y = 5.5,srt=90)

legend(-.2,11, legend=c("Donors", "Affluent"), col=c("black","light grey"), pch=c(16,18),cex=.75)

# republicans
for(i in 1: length(varlist_general)){
  donor_row <- reg1a %>%
    filter(term == varlist_names[varlist_general[nrows-i+1]], model == "Donor")
  affluent_row <- reg1a %>%
    filter(term == varlist_names[varlist_general[nrows-i+1]], model == "Affluent")
  
  text(x=0.5,y=i+3+length(varlist_general),labels=donor_row$tstat,cex=.75)
  
  # point estimate
  points(x=donor_row$estimate, y=i+3+length(varlist_general)+offset,pch=16)
  points(x=affluent_row$estimate, y=i+3+length(varlist_general)-offset, col = "GREY", pch = 18)
  
  segments(x0 = donor_row$LCI, y0 = i+3+length(varlist_general)+offset, x1 = donor_row$UCI, y1 = i+3+length(varlist_general)+offset)
  segments(x0 = affluent_row$LCI, y0 = i+3+length(varlist_general)-offset, x1 = affluent_row$UCI, y1 = i+3+length(varlist_general)-offset, col = "grey")
}

text(labels=rev(varlist_names),x= rep(-.4,times=length(varlist_general)),
     y=3+length(varlist_general)+seq(1,length(varlist_general)),cex=textsize,pos=4)
text(labels = "Republicans", x = -.4, y = 16,srt=90)
text(labels = "More Conservative", x = -.15, y = 4+length(varlist_general)+nrows+1,cex=.75)
text(labels = "More Liberal", x = .1, y = 4+length(varlist_general)+nrows+1,cex=.75)
text(labels = "More Conservative", x = -.15, y = 1,cex=.75)
text(labels = "More Liberal", x = .1, y = 1,cex=.75)
dev.off()




##############################################################################################################
#Figure L3: Differences in Donor, Affluent, and General Population Policy Views on Domestic Issues by Party Using an additive Index
##############################################################################################################


# Republicans Regression
dat1a <- dat %>%
  filter(republican==1) %>%
  mutate(sample=as.factor(sample)) %>%
  mutate(sample=relevel(sample, ref="Gen Pop")) %>%
  drop_na(f_01_minwagejoint,i_01_taxes1,f_01_tanfjoint,f_01_sumenvironment,i_01_health3,f_01_abortionjoint,i_01_rguncontrol) %>%
  mutate(AddIndexD = (f_01_minwagejoint + i_01_taxes1 + f_01_tanfjoint + f_01_sumenvironment + i_01_health3 + f_01_abortionjoint + i_01_rguncontrol)/7,
         AddIndexG = (i_01_rtrade + i_01_risolation + i_01_immigration5/5 + f_01_rdefensejoint/7)/4)

rawdat1a <- dat1a %>%
  dplyr::select(sample,fa_all,fa_global,AddIndexD,AddIndexG) %>%  
  pivot_longer(names_to = "Variable", cols = c(fa_all,fa_global,AddIndexD,AddIndexG)) %>%
  mutate(value = scale(value)) %>%
  dplyr::select(sample,Variable,value) %>%
  drop_na()

reg1a <- rawdat1a %>%
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ sample, data = .))) %>% # run model for each variable
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(model=recode(model,
                      sampleAffluent = "Affluent",
                      sampleDonor = "Donor")) %>%
  arrange(factor(model, levels=c("Donor","Affluent"))) %>% 
  arrange(factor(term, levels=c("fa_all","fa_global","AddIndexD","AddIndexG")))%>%
  mutate(model=factor(model, levels=c("Donor", "Affluent"))) %>%
  mutate(term=recode(term,
                     fa_all="Domestic Factor Score",
                     fa_global="Globalism Factor Score",
                     AddIndexD="Domestic Index Average",
                     AddIndexG="Globalism Index Average",)) %>%
  mutate(term=factor(term, levels=c("Domestic Factor Score", 
                                    "Domestic Index Average",
                                    "Globalism Factor Score",
                                    "Globalism Index Average"))) %>%
  mutate(LCI=estimate-std.error*1.96) %>%
  mutate(UCI=estimate+std.error*1.96)

diff1a <- rawdat1a %>%
  filter(sample == "Donor" | sample == "Affluent") %>%
  mutate(sample=relevel(sample, ref="Affluent")) %>% 
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ sample, data = .))) %>%
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(tstat = format(abs(round(statistic,digits=2)),nsmall=2)) %>%
  mutate(term=recode(term,
                     fa_all="Domestic Factor Score",
                     fa_global="Globalism Factor Score",
                     AddIndexD="Domestic Index Average",
                     AddIndexG="Globalism Index Average")) %>%
  dplyr::select(term,tstat)

reg1a = left_join(reg1a,diff1a)

# Demorats Regression
dat1b <- dat %>%
  filter(democrat==1) %>%
  mutate(sample=as.factor(sample)) %>%
  mutate(sample=relevel(sample, ref="Gen Pop")) %>%
  drop_na(f_01_minwagejoint,i_01_taxes1,f_01_tanfjoint,f_01_sumenvironment,i_01_health3,f_01_abortionjoint,i_01_rguncontrol) %>%
  mutate(AddIndexD = (f_01_minwagejoint + i_01_taxes1 + f_01_tanfjoint + f_01_sumenvironment + i_01_health3 + f_01_abortionjoint + i_01_rguncontrol)/7,
         AddIndexG = (i_01_rtrade + i_01_risolation + i_01_immigration5/5 + f_01_rdefensejoint/7)/4)

rawdat1b <- dat1b %>%
  dplyr::select(sample,fa_all,fa_global,AddIndexD,AddIndexG) %>%  
  pivot_longer(names_to = "Variable", cols = c(fa_all,fa_global,AddIndexD,AddIndexG)) %>%
  mutate(value = scale(value)) %>%
  dplyr::select(sample,Variable,value) %>%
  drop_na()

reg1b <- rawdat1b %>%
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ sample, data = .))) %>% # run model for each variable
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(model=recode(model,
                      sampleAffluent = "Affluent",
                      sampleDonor = "Donor")) %>%
  arrange(factor(model, levels=c("Donor","Affluent"))) %>% 
  arrange(factor(term, levels=c("fa_all","fa_global","AddIndexD","AddIndexG")))%>%
  mutate(model=factor(model, levels=c("Donor", "Affluent"))) %>%
  mutate(term=recode(term,
                     fa_all="Domestic Factor Score",
                     fa_global="Globalism Factor Score",
                     AddIndexD="Domestic Index Average",
                     AddIndexG="Globalism Index Average",)) %>%
  mutate(term=factor(term, levels=c("Domestic Factor Score", 
                                    "Domestic Index Average",
                                    "Globalism Factor Score",
                                    "Globalism Index Average"))) %>%
  mutate(LCI=estimate-std.error*1.96) %>%
  mutate(UCI=estimate+std.error*1.96)

diff1b <- rawdat1b %>%
  filter(sample == "Donor" | sample == "Affluent") %>%
  mutate(sample=relevel(sample, ref="Affluent")) %>% 
  group_by(Variable) %>% # group by variable
  do(broom::tidy(lm(value ~ sample, data = .))) %>%
  rename(model=term) %>%
  rename(term=Variable) %>%
  filter(model != "(Intercept)") %>%
  mutate(tstat = format(abs(round(statistic,digits=2)),nsmall=2)) %>%
  mutate(term=recode(term,
                     fa_all="Domestic Factor Score",
                     fa_global="Globalism Factor Score",
                     AddIndexD="Domestic Index Average",
                     AddIndexG="Globalism Index Average")) %>%
  dplyr::select(term,tstat)

reg1b = left_join(reg1b,diff1b)


##############
# Now Make figure
##############

varlist_names <- c(fa_all="Factor Score",
                   f_01_minwagejoint="Increase Minimum Wage",
                   i_01_taxes1="Incr. Top Marginal Tax Rate",
                   f_01_tanfjoint="Increase TANF Spending",
                   f_01_sumenvironment="Pro Environmentalism",
                   i_01_health3="Incr. Govt Role in Health Care",
                   f_01_abortionjoint="Fewer Abortion Restrictions",
                   i_01_rguncontrol="More Gun Control")

varlist_general = c("Domestic Factor Score","Domestic Index Average","Globalism Factor Score","Globalism Index Average")

nrows <- length(varlist_general)
offset <- .2

pdf(file= paste(outdir_figures, "SI_FigureL3_MAIN_Figure1_Index.pdf", sep = ""))

plot(x=c(-.5,.5),y=c(1,2*length(varlist_general)+5),type="n",axes=FALSE,
     xlab="Difference from Copartisan \n  General Population Mean (and 95% CI)",
     ylab="",
     main = "Average Policy Differences \n Among Donors, Affluent, and General Public")
abline(v=seq(-.3,.5,by=.05),lty=2,col="light grey")
abline(v=0)
axis(1,at=seq(-.3,.5,by=.05),
     labels=c(-.3,-.25,-.2,-.15,-.1,-.05,0,.05,.1,.15,.2,.25,.3,.35,.4,.45,.5))

# democrats
for(i in 1: length(varlist_general)){
  donor_row <- reg1b %>%
    filter(term == varlist_general[nrows-i+1], model == "Donor")
  affluent_row <- reg1b %>%
    filter(term == varlist_general[nrows-i+1], model == "Affluent")
  
  text(x=0.5,y=i+1,labels=donor_row$tstat,cex=.75)
  
  # point estimate
  points(x=donor_row$estimate, y=i+1+offset,pch=16)
  points(x=affluent_row$estimate, y=i+1-offset, col = "GREY", pch = 18)
  
  segments(x0 = donor_row$LCI, y0 = i+1+offset, x1 = donor_row$UCI, y1 = i+1+offset)
  segments(x0 = affluent_row$LCI, y0 = i+1-offset, x1 = affluent_row$UCI, y1 = i+1-offset, col = "grey")
}

text(labels=rev(varlist_general),x=rep(-.4,times=length(varlist_general)),
     y=1+seq(1,length(varlist_general)),cex=textsize,pos=4)
text(labels = "Democrats", x = -.4, y = 2.5,srt=90)

legend(-.2,7, legend=c("Donors", "Affluent"), col=c("black","light grey"), pch=c(16,18),cex=.75)

# republicans
for(i in 1: length(varlist_general)){
  donor_row <- reg1a %>%
    filter(term == varlist_general[nrows-i+1], model == "Donor")
  affluent_row <- reg1a %>%
    filter(term == varlist_general[nrows-i+1], model == "Affluent")
  
  text(x=0.5,y=i+3+length(varlist_general),labels=donor_row$tstat,cex=.75)
  
  # point estimate
  points(x=donor_row$estimate, y=i+3+length(varlist_general)+offset,pch=16)
  points(x=affluent_row$estimate, y=i+3+length(varlist_general)-offset, col = "GREY", pch = 18)
  
  segments(x0 = donor_row$LCI, y0 = i+3+length(varlist_general)+offset, x1 = donor_row$UCI, y1 = i+3+length(varlist_general)+offset)
  segments(x0 = affluent_row$LCI, y0 = i+3+length(varlist_general)-offset, x1 = affluent_row$UCI, y1 = i+3+length(varlist_general)-offset, col = "grey")
}

text(labels=rev(varlist_general),x= rep(-.4,times=length(varlist_general)),
     y=3+length(varlist_general)+seq(1,length(varlist_general)),cex=textsize,pos=4)
text(labels = "Republicans", x = -.4, y = 9,srt=90)
text(labels = "More Conservative", x = -.15, y = 4+length(varlist_general)+nrows+1,cex=.75)
text(labels = "More Liberal", x = .1, y = 4+length(varlist_general)+nrows+1,cex=.75)
text(labels = "More Conservative", x = -.15, y = 1,cex=.75)
text(labels = "More Liberal", x = .1, y = 1,cex=.75)
dev.off()


